# win32_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 #include "../stdafx.h"
    00013 #include "../openttd.h"
    00014 #include "../gfx_func.h"
    00015 #include "../os/windows/win32.h"
    00016 #include "../rev.h"
    00017 #include "../blitter/factory.hpp"
    00018 #include "../network/network.h"
    00019 #include "../core/math_func.hpp"
    00020 #include "../core/random_func.hpp"
    00021 #include "../texteff.hpp"
    00022 #include "win32_v.h"
    00023 #include <windows.h>
    00024
    00025 static struct {
    00026   HWND main_wnd;
    00027   HBITMAP dib_sect;
    00028   void *buffer_bits;
    00029   HPALETTE gdi_palette;
    00030   int width;
    00031   int height;
    00032   int width_org;
    00033   int height_org;
    00034   bool fullscreen;
    00035   bool has_focus;
    00036   bool running;
    00037 } _wnd;
    00038
    00039 bool _force_full_redraw;
    00040 bool _window_maximize;
    00041 uint _display_hz;
    00042 uint _fullscreen_bpp;
    00043 static Dimension _bck_resolution;
    00044 #if !defined(UNICODE)
    00045 uint _codepage;
    00046 #endif
    00047
    00048 static void MakePalette()
    00049 {
    00050   LOGPALETTE *pal;
    00051   uint i;
    00052
    00053   pal = (LOGPALETTE*)alloca(sizeof(LOGPALETTE) + (256 - 1) * sizeof(PALETTEENTRY));
    00054
    00055   pal->palVersion = 0x300;
    00056   pal->palNumEntries = 256;
    00057
    00058   for (i = 0; i != 256; i++) {
    00059     pal->palPalEntry[i].peRed   = _cur_palette[i].r;
    00060     pal->palPalEntry[i].peGreen = _cur_palette[i].g;
    00061     pal->palPalEntry[i].peBlue  = _cur_palette[i].b;
    00062     pal->palPalEntry[i].peFlags = 0;
    00063
    00064   }
    00065   _wnd.gdi_palette = CreatePalette(pal);
    00066   if (_wnd.gdi_palette == NULL) usererror("CreatePalette failed!\n");
    00067 }
    00068
    00069 static void UpdatePalette(HDC dc, uint start, uint count)
    00070 {
    00071   RGBQUAD rgb[256];
    00072   uint i;
    00073
    00074   for (i = 0; i != count; i++) {
    00075     rgb[i].rgbRed   = _cur_palette[start + i].r;
    00076     rgb[i].rgbGreen = _cur_palette[start + i].g;
    00077     rgb[i].rgbBlue  = _cur_palette[start + i].b;
    00078     rgb[i].rgbReserved = 0;
    00079   }
    00080
    00081   SetDIBColorTable(dc, start, count, rgb);
    00082 }
    00083
    00084 struct VkMapping {
    00085   byte vk_from;
    00086   byte vk_count;
    00087   byte map_to;
    00088 };
    00089
    00090 #define AS(x, z) {x, 0, z}
    00091 #define AM(x, y, z, w) {x, y - x, z}
    00092
    00093 static const VkMapping _vk_mapping[] = {
    00094   /* Pageup stuff + up/down */
    00095   AM(VK_PRIOR, VK_DOWN, WKC_PAGEUP, WKC_DOWN),
    00096   /* Map letters & digits */
    00097   AM('A', 'Z', 'A', 'Z'),
    00098   AM('0', '9', '0', '9'),
    00099
    00100   AS(VK_ESCAPE,   WKC_ESC),
    00101   AS(VK_PAUSE,    WKC_PAUSE),
    00102   AS(VK_BACK,     WKC_BACKSPACE),
    00103   AM(VK_INSERT,   VK_DELETE, WKC_INSERT, WKC_DELETE),
    00104
    00105   AS(VK_SPACE,    WKC_SPACE),
    00106   AS(VK_RETURN,   WKC_RETURN),
    00107   AS(VK_TAB,      WKC_TAB),
    00108
    00109   /* Function keys */
    00110   AM(VK_F1, VK_F12, WKC_F1, WKC_F12),
    00111
    00112   /* Numeric part */
    00113   AM(VK_NUMPAD0, VK_NUMPAD9, '0', '9'),
    00114   AS(VK_DIVIDE,   WKC_NUM_DIV),
    00115   AS(VK_MULTIPLY, WKC_NUM_MUL),
    00116   AS(VK_SUBTRACT, WKC_NUM_MINUS),
    00117   AS(VK_ADD,      WKC_NUM_PLUS),
    00118   AS(VK_DECIMAL,  WKC_NUM_DECIMAL),
    00119
    00120   /* Other non-letter keys */
    00121   AS(0xBF,  WKC_SLASH),
    00122   AS(0xBA,  WKC_SEMICOLON),
    00123   AS(0xBB,  WKC_EQUALS),
    00124   AS(0xDB,  WKC_L_BRACKET),
    00125   AS(0xDC,  WKC_BACKSLASH),
    00126   AS(0xDD,  WKC_R_BRACKET),
    00127
    00128   AS(0xDE,  WKC_SINGLEQUOTE),
    00129   AS(0xBC,  WKC_COMMA),
    00130   AS(0xBD,  WKC_MINUS),
    00131   AS(0xBE,  WKC_PERIOD)
    00132 };
    00133
    00134 static uint MapWindowsKey(uint sym)
    00135 {
    00136   const VkMapping *map;
    00137   uint key = 0;
    00138
    00139   for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
    00140     if ((uint)(sym - map->vk_from) <= map->vk_count) {
    00141       key = sym - map->vk_from + map->map_to;
    00142       break;
    00143     }
    00144   }
    00145
    00146   if (GetAsyncKeyState(VK_SHIFT)   < 0) key |= WKC_SHIFT;
    00147   if (GetAsyncKeyState(VK_CONTROL) < 0) key |= WKC_CTRL;
    00148   if (GetAsyncKeyState(VK_MENU)    < 0) key |= WKC_ALT;
    00149   return key;
    00150 }
    00151
    00152 static bool AllocateDibSection(int w, int h);
    00153
    00154 static void ClientSizeChanged(int w, int h)
    00155 {
    00156   /* allocate new dib section of the new size */
    00157   if (AllocateDibSection(w, h)) {
    00158     /* mark all palette colors dirty */
    00159     _pal_first_dirty = 0;
    00160     _pal_count_dirty = 256;
    00161
    00162     BlitterFactoryBase::GetCurrentBlitter()->PostResize();
    00163
    00164     GameSizeChanged();
    00165
    00166     /* redraw screen */
    00167     if (_wnd.running) {
    00168       _screen.dst_ptr = _wnd.buffer_bits;
    00169       UpdateWindows();
    00170     }
    00171   }
    00172 }
    00173
    00174 #ifdef _DEBUG
    00175 /* Keep this function here..
    00176  * It allows you to redraw the screen from within the MSVC debugger */
    00177 int RedrawScreenDebug()
    00178 {
    00179   HDC dc, dc2;
    00180   static int _fooctr;
    00181   HBITMAP old_bmp;
    00182   HPALETTE old_palette;
    00183
    00184   _screen.dst_ptr = _wnd.buffer_bits;
    00185   UpdateWindows();
    00186
    00187   dc = GetDC(_wnd.main_wnd);
    00188   dc2 = CreateCompatibleDC(dc);
    00189
    00190   old_bmp = (HBITMAP)SelectObject(dc2, _wnd.dib_sect);
    00191   old_palette = SelectPalette(dc, _wnd.gdi_palette, FALSE);
    00192   BitBlt(dc, 0, 0, _wnd.width, _wnd.height, dc2, 0, 0, SRCCOPY);
    00193   SelectPalette(dc, old_palette, TRUE);
    00194   SelectObject(dc2, old_bmp);
    00195   DeleteDC(dc2);
    00196   ReleaseDC(_wnd.main_wnd, dc);
    00197
    00198   return _fooctr++;
    00199 }
    00200 #endif
    00201
    00202 /* Windows 95 will not have a WM_MOUSELEAVE message, so define it if needed */
    00203 #if !defined(WM_MOUSELEAVE)
    00204 #define WM_MOUSELEAVE 0x02A3
    00205 #endif
    00206 #define TID_POLLMOUSE 1
    00207 #define MOUSE_POLL_DELAY 75
    00208
    00209 static void CALLBACK TrackMouseTimerProc(HWND hwnd, UINT msg, UINT event, DWORD time)
    00210 {
    00211   RECT rc;
    00212   POINT pt;
    00213
    00214   /* Get the rectangle of our window and translate it to screen coordinates.
    00215    * Compare this with the current screen coordinates of the mouse and if it
    00216    * falls outside of the area or our window we have left the window. */
    00217   GetClientRect(hwnd, &rc);
    00218   MapWindowPoints(hwnd, HWND_DESKTOP, (LPPOINT)(LPRECT)&rc, 2);
    00219   GetCursorPos(&pt);
    00220
    00221   if (!PtInRect(&rc, pt) || (WindowFromPoint(pt) != hwnd)) {
    00222     KillTimer(hwnd, event);
    00223     PostMessage(hwnd, WM_MOUSELEAVE, 0, 0L);
    00224   }
    00225 }
    00226
    00227 bool VideoDriver_Win32::MakeWindow(bool full_screen)
    00228 {
    00229   _fullscreen = full_screen;
    00230
    00231   /* recreate window? */
    00232   if ((full_screen || _wnd.fullscreen) && _wnd.main_wnd) {
    00233     DestroyWindow(_wnd.main_wnd);
    00234     _wnd.main_wnd = 0;
    00235   }
    00236
    00237 #if defined(WINCE)
    00238   /* WinCE is always fullscreen */
    00239 #else
    00240   if (full_screen) {
    00241     DEVMODE settings;
    00242
    00243     /* Make sure we are always at least the screen-depth of the blitter */
    00244     if (_fullscreen_bpp < BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth()) _fullscreen_bpp = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
    00245
    00246     memset(&settings, 0, sizeof(settings));
    00247     settings.dmSize = sizeof(settings);
    00248     settings.dmFields =
    00249       (_fullscreen_bpp != 0 ? DM_BITSPERPEL : 0) |
    00250       DM_PELSWIDTH |
    00251       DM_PELSHEIGHT |
    00252       (_display_hz != 0 ? DM_DISPLAYFREQUENCY : 0);
    00253     settings.dmBitsPerPel = _fullscreen_bpp;
    00254     settings.dmPelsWidth  = _wnd.width_org;
    00255     settings.dmPelsHeight = _wnd.height_org;
    00256     settings.dmDisplayFrequency = _display_hz;
    00257
    00258     /* Test fullscreen with current resolution, if it fails use desktop resolution. */
    00259     if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
    00260       RECT r;
    00261       GetWindowRect(GetDesktopWindow(), &r);
    00262       return this->ChangeResolution(r.right - r.left, r.bottom - r.top);
    00263     }
    00264
    00265     if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
    00266       this->MakeWindow(false);  // don't care about the result
    00267       return false;  // the request failed
    00268     }
    00269   } else if (_wnd.fullscreen) {
    00270     /* restore display? */
    00271     ChangeDisplaySettings(NULL, 0);
    00272   }
    00273 #endif
    00274
    00275   {
    00276     RECT r;
    00277     DWORD style, showstyle;
    00278     int x, y, w, h;
    00279
    00280     showstyle = SW_SHOWNORMAL;
    00281     _wnd.fullscreen = full_screen;
    00282     if (_wnd.fullscreen) {
    00283       style = WS_POPUP;
    00284       SetRect(&r, 0, 0, _wnd.width_org, _wnd.height_org);
    00285     } else {
    00286       style = WS_OVERLAPPEDWINDOW;
    00287       /* On window creation, check if we were in maximize mode before */
    00288       if (_window_maximize) showstyle = SW_SHOWMAXIMIZED;
    00289       SetRect(&r, 0, 0, _wnd.width, _wnd.height);
    00290     }
    00291
    00292 #if !defined(WINCE)
    00293     AdjustWindowRect(&r, style, FALSE);
    00294 #endif
    00295     w = r.right - r.left;
    00296     h = r.bottom - r.top;
    00297     x = (GetSystemMetrics(SM_CXSCREEN) - w) / 2;
    00298     y = (GetSystemMetrics(SM_CYSCREEN) - h) / 2;
    00299
    00300     if (_wnd.main_wnd) {
    00301       ShowWindow(_wnd.main_wnd, SW_SHOWNORMAL); // remove maximize-flag
    00302       SetWindowPos(_wnd.main_wnd, 0, x, y, w, h, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
    00303     } else {
    00304       TCHAR Windowtitle[50];
    00305
    00306       _sntprintf(Windowtitle, lengthof(Windowtitle), _T("OpenTTD %s"), MB_TO_WIDE(_openttd_revision));
    00307
    00308       _wnd.main_wnd = CreateWindow(_T("OTTD"), Windowtitle, style, x, y, w, h, 0, 0, GetModuleHandle(NULL), 0);
    00309       if (_wnd.main_wnd == NULL) usererror("CreateWindow failed");
    00310       ShowWindow(_wnd.main_wnd, showstyle);
    00311     }
    00312   }
    00313
    00314   BlitterFactoryBase::GetCurrentBlitter()->PostResize();
    00315
    00316   GameSizeChanged(); // invalidate all windows, force redraw
    00317   return true; // the request succedded
    00318 }
    00319
    00320 static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
    00321 {
    00322   static uint32 keycode = 0;
    00323   static bool console = false;
    00324
    00325   switch (msg) {
    00326     case WM_CREATE:
    00327       SetTimer(hwnd, TID_POLLMOUSE, MOUSE_POLL_DELAY, (TIMERPROC)TrackMouseTimerProc);
    00328       break;
    00329
    00330     case WM_PAINT: {
    00331       PAINTSTRUCT ps;
    00332       HDC dc, dc2;
    00333       HBITMAP old_bmp;
    00334       HPALETTE old_palette;
    00335
    00336       BeginPaint(hwnd, &ps);
    00337       dc = ps.hdc;
    00338       dc2 = CreateCompatibleDC(dc);
    00339       old_bmp = (HBITMAP)SelectObject(dc2, _wnd.dib_sect);
    00340       old_palette = SelectPalette(dc, _wnd.gdi_palette, FALSE);
    00341
    00342       if (_pal_count_dirty != 0) {
    00343         Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    00344
    00345         switch (blitter->UsePaletteAnimation()) {
    00346           case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
    00347             UpdatePalette(dc2, _pal_first_dirty, _pal_count_dirty);
    00348             break;
    00349
    00350           case Blitter::PALETTE_ANIMATION_BLITTER:
    00351             blitter->PaletteAnimate(_pal_first_dirty, _pal_count_dirty);
    00352             break;
    00353
    00354           case Blitter::PALETTE_ANIMATION_NONE:
    00355             break;
    00356
    00357           default:
    00358             NOT_REACHED();
    00359         }
    00360         _pal_count_dirty = 0;
    00361       }
    00362
    00363       BitBlt(dc, 0, 0, _wnd.width, _wnd.height, dc2, 0, 0, SRCCOPY);
    00364       SelectPalette(dc, old_palette, TRUE);
    00365       SelectObject(dc2, old_bmp);
    00366       DeleteDC(dc2);
    00367       EndPaint(hwnd, &ps);
    00368       return 0;
    00369     }
    00370
    00371     case WM_PALETTECHANGED:
    00372       if ((HWND)wParam == hwnd) return 0;
    00373       /* FALL THROUGH */
    00374
    00375     case WM_QUERYNEWPALETTE: {
    00376       HDC hDC = GetWindowDC(hwnd);
    00377       HPALETTE hOldPalette = SelectPalette(hDC, _wnd.gdi_palette, FALSE);
    00378       UINT nChanged = RealizePalette(hDC);
    00379
    00380       SelectPalette(hDC, hOldPalette, TRUE);
    00381       ReleaseDC(hwnd, hDC);
    00382       if (nChanged) InvalidateRect(hwnd, NULL, FALSE);
    00383       return 0;
    00384     }
    00385
    00386     case WM_CLOSE:
    00387       HandleExitGameRequest();
    00388       return 0;
    00389
    00390     case WM_DESTROY:
    00391       if (_window_maximize) _cur_resolution = _bck_resolution;
    00392       return 0;
    00393
    00394     case WM_LBUTTONDOWN:
    00395       SetCapture(hwnd);
    00396       _left_button_down = true;
    00397       HandleMouseEvents();
    00398       return 0;
    00399
    00400     case WM_LBUTTONUP:
    00401       ReleaseCapture();
    00402       _left_button_down = false;
    00403       _left_button_clicked = false;
    00404       HandleMouseEvents();
    00405       return 0;
    00406
    00407     case WM_RBUTTONDOWN:
    00408       SetCapture(hwnd);
    00409       _right_button_down = true;
    00410       _right_button_clicked = true;
    00411       HandleMouseEvents();
    00412       return 0;
    00413
    00414     case WM_RBUTTONUP:
    00415       ReleaseCapture();
    00416       _right_button_down = false;
    00417       HandleMouseEvents();
    00418       return 0;
    00419
    00420     case WM_MOUSELEAVE:
    00421       UndrawMouseCursor();
    00422       _cursor.in_window = false;
    00423
    00424       if (!_left_button_down && !_right_button_down) MyShowCursor(true);
    00425       return 0;
    00426
    00427     case WM_MOUSEMOVE: {
    00428       int x = (int16)LOWORD(lParam);
    00429       int y = (int16)HIWORD(lParam);
    00430       POINT pt;
    00431
    00432       /* If the mouse was not in the window and it has moved it means it has
    00433        * come into the window, so start drawing the mouse. Also start
    00434        * tracking the mouse for exiting the window */
    00435       if (!_cursor.in_window) {
    00436         _cursor.in_window = true;
    00437         SetTimer(hwnd, TID_POLLMOUSE, MOUSE_POLL_DELAY, (TIMERPROC)TrackMouseTimerProc);
    00438
    00439         DrawMouseCursor();
    00440       }
    00441
    00442       if (_cursor.fix_at) {
    00443         int dx = x - _cursor.pos.x;
    00444         int dy = y - _cursor.pos.y;
    00445         if (dx != 0 || dy != 0) {
    00446           _cursor.delta.x = dx;
    00447           _cursor.delta.y = dy;
    00448
    00449           pt.x = _cursor.pos.x;
    00450           pt.y = _cursor.pos.y;
    00451
    00452           ClientToScreen(hwnd, &pt);
    00453           SetCursorPos(pt.x, pt.y);
    00454         }
    00455       } else {
    00456         _cursor.delta.x = x - _cursor.pos.x;
    00457         _cursor.delta.y = y - _cursor.pos.y;
    00458         _cursor.pos.x = x;
    00459         _cursor.pos.y = y;
    00460         _cursor.dirty = true;
    00461       }
    00462       MyShowCursor(false);
    00463       HandleMouseEvents();
    00464       return 0;
    00465     }
    00466
    00467 #if !defined(UNICODE)
    00468     case WM_INPUTLANGCHANGE: {
    00469       TCHAR locale[6];
    00470       LCID lcid = GB(lParam, 0, 16);
    00471
    00472       int len = GetLocaleInfo(lcid, LOCALE_IDEFAULTANSICODEPAGE, locale, lengthof(locale));
    00473       if (len != 0) _codepage = _ttoi(locale);
    00474       return 1;
    00475     }
    00476 #endif /* UNICODE */
    00477
    00478     case WM_DEADCHAR:
    00479       console = GB(lParam, 16, 8) == 41;
    00480       return 0;
    00481
    00482     case WM_CHAR: {
    00483       uint scancode = GB(lParam, 16, 8);
    00484       uint charcode = wParam;
    00485
    00486       /* If the console key is a dead-key, we need to press it twice to get a WM_CHAR message.
    00487        * But we then get two WM_CHAR messages, so ignore the first one */
    00488       if (console && scancode == 41) {
    00489         console = false;
    00490         return 0;
    00491       }
    00492
    00493 #if !defined(UNICODE)
    00494       wchar_t w;
    00495       int len = MultiByteToWideChar(_codepage, 0, (char*)&charcode, 1, &w, 1);
    00496       charcode = len == 1 ? w : 0;
    00497 #endif /* UNICODE */
    00498
    00499       /* No matter the keyboard layout, we will map the '~' to the console */
    00500       scancode = scancode == 41 ? (int)WKC_BACKQUOTE : keycode;
    00501       HandleKeypress(GB(charcode, 0, 16) | (scancode << 16));
    00502       return 0;
    00503     }
    00504
    00505     case WM_KEYDOWN: {
    00506       keycode = MapWindowsKey(wParam);
    00507
    00508       /* Silently drop all messages handled by WM_CHAR. */
    00509       MSG msg;
    00510       if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
    00511         if (msg.message == WM_CHAR && GB(lParam, 16, 8) == GB(msg.lParam, 16, 8)) {
    00512           return 0;
    00513         }
    00514       }
    00515
    00516       HandleKeypress(0 | (keycode << 16));
    00517       return 0;
    00518     }
    00519
    00520     case WM_SYSKEYDOWN: // user presses F10 or Alt, both activating the title-menu
    00521       switch (wParam) {
    00522         case VK_RETURN:
    00523         case 'F': // Full Screen on ALT + ENTER/F
    00524           ToggleFullScreen(!_wnd.fullscreen);
    00525           return 0;
    00526
    00527         case VK_MENU: // Just ALT
    00528           return 0; // do nothing
    00529
    00530         case VK_F10: // F10, ignore activation of menu
    00531           HandleKeypress(MapWindowsKey(wParam) << 16);
    00532           return 0;
    00533
    00534         default: // ALT in combination with something else
    00535           HandleKeypress(MapWindowsKey(wParam) << 16);
    00536           break;
    00537       }
    00538       break;
    00539
    00540     case WM_SIZE:
    00541       if (wParam != SIZE_MINIMIZED) {
    00542         /* Set maximized flag when we maximize (obviously), but also when we
    00543          * switched to fullscreen from a maximized state */
    00544         _window_maximize = (wParam == SIZE_MAXIMIZED || (_window_maximize && _fullscreen));
    00545         if (_window_maximize) _bck_resolution = _cur_resolution;
    00546         ClientSizeChanged(LOWORD(lParam), HIWORD(lParam));
    00547       }
    00548       return 0;
    00549
    00550 #if !defined(WINCE)
    00551     case WM_SIZING: {
    00552       RECT *r = (RECT*)lParam;
    00553       RECT r2;
    00554       int w, h;
    00555
    00556       SetRect(&r2, 0, 0, 0, 0);
    00557       AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
    00558
    00559       w = r->right - r->left - (r2.right - r2.left);
    00560       h = r->bottom - r->top - (r2.bottom - r2.top);
    00561       w = max(w, 64);
    00562       h = max(h, 64);
    00563       SetRect(&r2, 0, 0, w, h);
    00564
    00565       AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
    00566       w = r2.right - r2.left;
    00567       h = r2.bottom - r2.top;
    00568
    00569       switch (wParam) {
    00570         case WMSZ_BOTTOM:
    00571           r->bottom = r->top + h;
    00572           break;
    00573
    00574         case WMSZ_BOTTOMLEFT:
    00575           r->bottom = r->top + h;
    00576           r->left = r->right - w;
    00577           break;
    00578
    00579         case WMSZ_BOTTOMRIGHT:
    00580           r->bottom = r->top + h;
    00581           r->right = r->left + w;
    00582           break;
    00583
    00584         case WMSZ_LEFT:
    00585           r->left = r->right - w;
    00586           break;
    00587
    00588         case WMSZ_RIGHT:
    00589           r->right = r->left + w;
    00590           break;
    00591
    00592         case WMSZ_TOP:
    00593           r->top = r->bottom - h;
    00594           break;
    00595
    00596         case WMSZ_TOPLEFT:
    00597           r->top = r->bottom - h;
    00598           r->left = r->right - w;
    00599           break;
    00600
    00601         case WMSZ_TOPRIGHT:
    00602           r->top = r->bottom - h;
    00603           r->right = r->left + w;
    00604           break;
    00605       }
    00606       return TRUE;
    00607     }
    00608 #endif
    00609
    00610 /* needed for wheel */
    00611 #if !defined(WM_MOUSEWHEEL)
    00612 # define WM_MOUSEWHEEL 0x020A
    00613 #endif  /* WM_MOUSEWHEEL */
    00614 #if !defined(GET_WHEEL_DELTA_WPARAM)
    00615 # define GET_WHEEL_DELTA_WPARAM(wparam) ((short)HIWORD(wparam))
    00616 #endif  /* GET_WHEEL_DELTA_WPARAM */
    00617
    00618     case WM_MOUSEWHEEL: {
    00619       int delta = GET_WHEEL_DELTA_WPARAM(wParam);
    00620
    00621       if (delta < 0) {
    00622         _cursor.wheel++;
    00623       } else if (delta > 0) {
    00624         _cursor.wheel--;
    00625       }
    00626       HandleMouseEvents();
    00627       return 0;
    00628     }
    00629
    00630     case WM_SETFOCUS:
    00631       _wnd.has_focus = true;
    00632       break;
    00633
    00634     case WM_KILLFOCUS:
    00635       _wnd.has_focus = false;
    00636       break;
    00637
    00638 #if !defined(WINCE)
    00639     case WM_ACTIVATE: {
    00640       /* Don't do anything if we are closing openttd */
    00641       if (_exit_game) break;
    00642
    00643       bool active = (LOWORD(wParam) != WA_INACTIVE);
    00644       bool minimized = (HIWORD(wParam) != 0);
    00645       if (_wnd.fullscreen) {
    00646         if (active && minimized) {
    00647           /* Restore the game window */
    00648           ShowWindow(hwnd, SW_RESTORE);
    00649           static_cast<VideoDriver_Win32 *>(_video_driver)->MakeWindow(true);
    00650         } else if (!active && !minimized) {
    00651           /* Minimise the window and restore desktop */
    00652           ShowWindow(hwnd, SW_MINIMIZE);
    00653           ChangeDisplaySettings(NULL, 0);
    00654         }
    00655       }
    00656       break;
    00657     }
    00658 #endif
    00659   }
    00660
    00661   return DefWindowProc(hwnd, msg, wParam, lParam);
    00662 }
    00663
    00664 static void RegisterWndClass()
    00665 {
    00666   static bool registered = false;
    00667
    00668   if (!registered) {
    00669     HINSTANCE hinst = GetModuleHandle(NULL);
    00670     WNDCLASS wnd = {
    00671       0,
    00672       WndProcGdi,
    00673       0,
    00674       0,
    00675       hinst,
    00676       LoadIcon(hinst, MAKEINTRESOURCE(100)),
    00677       LoadCursor(NULL, IDC_ARROW),
    00678       0,
    00679       0,
    00680       _T("OTTD")
    00681     };
    00682
    00683     registered = true;
    00684     if (!RegisterClass(&wnd)) usererror("RegisterClass failed");
    00685   }
    00686 }
    00687
    00688 static bool AllocateDibSection(int w, int h)
    00689 {
    00690   BITMAPINFO *bi;
    00691   HDC dc;
    00692   int bpp = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
    00693
    00694   w = max(w, 64);
    00695   h = max(h, 64);
    00696
    00697   if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");
    00698
    00699   if (w == _screen.width && h == _screen.height) return false;
    00700
    00701   _screen.width = w;
    00702   _screen.pitch = (bpp == 8) ? Align(w, 4) : w;
    00703   _screen.height = h;
    00704   bi = (BITMAPINFO*)alloca(sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256);
    00705   memset(bi, 0, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256);
    00706   bi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    00707
    00708   bi->bmiHeader.biWidth = _wnd.width = w;
    00709   bi->bmiHeader.biHeight = -(_wnd.height = h);
    00710
    00711   bi->bmiHeader.biPlanes = 1;
    00712   bi->bmiHeader.biBitCount = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
    00713   bi->bmiHeader.biCompression = BI_RGB;
    00714
    00715   if (_wnd.dib_sect) DeleteObject(_wnd.dib_sect);
    00716
    00717   dc = GetDC(0);
    00718   _wnd.dib_sect = CreateDIBSection(dc, bi, DIB_RGB_COLORS, (VOID**)&_wnd.buffer_bits, NULL, 0);
    00719   if (_wnd.dib_sect == NULL) usererror("CreateDIBSection failed");
    00720   ReleaseDC(0, dc);
    00721
    00722   return true;
    00723 }
    00724
    00725 static const Dimension default_resolutions[] = {
    00726   {  640,  480 },
    00727   {  800,  600 },
    00728   { 1024,  768 },
    00729   { 1152,  864 },
    00730   { 1280,  800 },
    00731   { 1280,  960 },
    00732   { 1280, 1024 },
    00733   { 1400, 1050 },
    00734   { 1600, 1200 },
    00735   { 1680, 1050 },
    00736   { 1920, 1200 }
    00737 };
    00738
    00739 static void FindResolutions()
    00740 {
    00741   uint n = 0;
    00742 #if defined(WINCE)
    00743   /* EnumDisplaySettingsW is only supported in CE 4.2+
    00744    * XXX -- One might argue that we assume 4.2+ on every system. Then we can use this function safely */
    00745 #else
    00746   uint i;
    00747   DEVMODEA dm;
    00748
    00749   /* XXX - EnumDisplaySettingsW crashes with unicows.dll on Windows95
    00750    * Doesn't really matter since we don't pass a string anyways, but still
    00751    * a letdown */
    00752   for (i = 0; EnumDisplaySettingsA(NULL, i, &dm) != 0; i++) {
    00753     if (dm.dmBitsPerPel == BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() &&
    00754         dm.dmPelsWidth >= 640 && dm.dmPelsHeight >= 480) {
    00755       uint j;
    00756
    00757       for (j = 0; j < n; j++) {
    00758         if (_resolutions[j].width == dm.dmPelsWidth && _resolutions[j].height == dm.dmPelsHeight) break;
    00759       }
    00760
    00761       /* In the previous loop we have checked already existing/added resolutions if
    00762        * they are the same as the new ones. If this is not the case (j == n); we have
    00763        * looped all and found none, add the new one to the list. If we have reached the
    00764        * maximum amount of resolutions, then quit querying the display */
    00765       if (j == n) {
    00766         _resolutions[j].width  = dm.dmPelsWidth;
    00767         _resolutions[j].height = dm.dmPelsHeight;
    00768         if (++n == lengthof(_resolutions)) break;
    00769       }
    00770     }
    00771   }
    00772 #endif
    00773
    00774   /* We have found no resolutions, show the default list */
    00775   if (n == 0) {
    00776     memcpy(_resolutions, default_resolutions, sizeof(default_resolutions));
    00777     n = lengthof(default_resolutions);
    00778   }
    00779
    00780   _num_resolutions = n;
    00781   SortResolutions(_num_resolutions);
    00782 }
    00783
    00784 static FVideoDriver_Win32 iFVideoDriver_Win32;
    00785
    00786 const char *VideoDriver_Win32::Start(const char * const *parm)
    00787 {
    00788   memset(&_wnd, 0, sizeof(_wnd));
    00789
    00790   RegisterWndClass();
    00791
    00792   MakePalette();
    00793
    00794   FindResolutions();
    00795
    00796   DEBUG(driver, 2, "Resolution for display: %ux%u", _cur_resolution.width, _cur_resolution.height);
    00797
    00798   /* fullscreen uses those */
    00799   _wnd.width_org  = _cur_resolution.width;
    00800   _wnd.height_org = _cur_resolution.height;
    00801
    00802   AllocateDibSection(_cur_resolution.width, _cur_resolution.height);
    00803   this->MakeWindow(_fullscreen);
    00804
    00805   MarkWholeScreenDirty();
    00806
    00807   return NULL;
    00808 }
    00809
    00810 void VideoDriver_Win32::Stop()
    00811 {
    00812   DeleteObject(_wnd.gdi_palette);
    00813   DeleteObject(_wnd.dib_sect);
    00814   DestroyWindow(_wnd.main_wnd);
    00815
    00816 #if !defined(WINCE)
    00817   if (_wnd.fullscreen) ChangeDisplaySettings(NULL, 0);
    00818 #endif
    00819   MyShowCursor(true);
    00820 }
    00821
    00822 void VideoDriver_Win32::MakeDirty(int left, int top, int width, int height)
    00823 {
    00824   RECT r = { left, top, left + width, top + height };
    00825
    00826   InvalidateRect(_wnd.main_wnd, &r, FALSE);
    00827 }
    00828
    00829 static void CheckPaletteAnim()
    00830 {
    00831   if (_pal_count_dirty == 0) return;
    00832
    00833   InvalidateRect(_wnd.main_wnd, NULL, FALSE);
    00834 }
    00835
    00836 void VideoDriver_Win32::MainLoop()
    00837 {
    00838   MSG mesg;
    00839   uint32 cur_ticks = GetTickCount();
    00840   uint32 last_cur_ticks = cur_ticks;
    00841   uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
    00842
    00843   _wnd.running = true;
    00844
    00845   for (;;) {
    00846     uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
    00847
    00848     while (PeekMessage(&mesg, NULL, 0, 0, PM_REMOVE)) {
    00849       InteractiveRandom(); // randomness
    00850       TranslateMessage(&mesg);
    00851       DispatchMessage(&mesg);
    00852     }
    00853     if (_exit_game) return;
    00854
    00855 #if defined(_DEBUG)
    00856     if (_wnd.has_focus && GetAsyncKeyState(VK_SHIFT) < 0 &&
    00857 #else
    00858     /* Speed up using TAB, but disable for ALT+TAB of course */
    00859     if (_wnd.has_focus && GetAsyncKeyState(VK_TAB) < 0 && GetAsyncKeyState(VK_MENU) >= 0 &&
    00860 #endif
    00861         !_networking && _game_mode != GM_MENU) {
    00862       _fast_forward |= 2;
    00863     } else if (_fast_forward & 2) {
    00864       _fast_forward = 0;
    00865     }
    00866
    00867     cur_ticks = GetTickCount();
    00868     if (cur_ticks >= next_tick || (_fast_forward && !_pause_mode) || cur_ticks < prev_cur_ticks) {
    00869       _realtime_tick += cur_ticks - last_cur_ticks;
    00870       last_cur_ticks = cur_ticks;
    00871       next_tick = cur_ticks + MILLISECONDS_PER_TICK;
    00872
    00873       bool old_ctrl_pressed = _ctrl_pressed;
    00874
    00875       _ctrl_pressed = _wnd.has_focus && GetAsyncKeyState(VK_CONTROL)<0;
    00876       _shift_pressed = _wnd.has_focus && GetAsyncKeyState(VK_SHIFT)<0;
    00877
    00878       /* determine which directional keys are down */
    00879       if (_wnd.has_focus) {
    00880         _dirkeys =
    00881           (GetAsyncKeyState(VK_LEFT) < 0 ? 1 : 0) +
    00882           (GetAsyncKeyState(VK_UP) < 0 ? 2 : 0) +
    00883           (GetAsyncKeyState(VK_RIGHT) < 0 ? 4 : 0) +
    00884           (GetAsyncKeyState(VK_DOWN) < 0 ? 8 : 0);
    00885       } else {
    00886         _dirkeys = 0;
    00887       }
    00888
    00889       if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
    00890
    00891       GameLoop();
    00892
    00893       if (_force_full_redraw) MarkWholeScreenDirty();
    00894
    00895 #if !defined(WINCE)
    00896       GdiFlush();
    00897 #endif
    00898       _screen.dst_ptr = _wnd.buffer_bits;
    00899       UpdateWindows();
    00900       CheckPaletteAnim();
    00901     } else {
    00902       Sleep(1);
    00903 #if !defined(WINCE)
    00904       GdiFlush();
    00905 #endif
    00906       _screen.dst_ptr = _wnd.buffer_bits;
    00907       NetworkDrawChatMessage();
    00908       DrawMouseCursor();
    00909     }
    00910   }
    00911 }
    00912
    00913 bool VideoDriver_Win32::ChangeResolution(int w, int h)
    00914 {
    00915   _wnd.width = _wnd.width_org = w;
    00916   _wnd.height = _wnd.height_org = h;
    00917
    00918   return this->MakeWindow(_fullscreen); // _wnd.fullscreen screws up ingame resolution switching
    00919 }
    00920
    00921 bool VideoDriver_Win32::ToggleFullscreen(bool full_screen)
    00922 {
    00923   return this->MakeWindow(full_screen);
    00924 }