# 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
    00232 bool VideoDriver_Win32::MakeWindow(bool full_screen)
    00233 {
    00234   _fullscreen = full_screen;
    00235
    00236   /* recreate window? */
    00237   if ((full_screen || _wnd.fullscreen) && _wnd.main_wnd) {
    00238     DestroyWindow(_wnd.main_wnd);
    00239     _wnd.main_wnd = 0;
    00240   }
    00241
    00242 #if defined(WINCE)
    00243   /* WinCE is always fullscreen */
    00244 #else
    00245   if (full_screen) {
    00246     DEVMODE settings;
    00247
    00248     /* Make sure we are always at least the screen-depth of the blitter */
    00249     if (_fullscreen_bpp < BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth()) _fullscreen_bpp = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
    00250
    00251     memset(&settings, 0, sizeof(settings));
    00252     settings.dmSize = sizeof(settings);
    00253     settings.dmFields =
    00254       (_fullscreen_bpp != 0 ? DM_BITSPERPEL : 0) |
    00255       DM_PELSWIDTH |
    00256       DM_PELSHEIGHT |
    00257       (_display_hz != 0 ? DM_DISPLAYFREQUENCY : 0);
    00258     settings.dmBitsPerPel = _fullscreen_bpp;
    00259     settings.dmPelsWidth  = _wnd.width_org;
    00260     settings.dmPelsHeight = _wnd.height_org;
    00261     settings.dmDisplayFrequency = _display_hz;
    00262
    00263     /* Test fullscreen with current resolution, if it fails use desktop resolution. */
    00264     if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
    00265       RECT r;
    00266       GetWindowRect(GetDesktopWindow(), &r);
    00267       return this->ChangeResolution(r.right - r.left, r.bottom - r.top);
    00268     }
    00269
    00270     if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
    00271       this->MakeWindow(false);  // don't care about the result
    00272       return false;  // the request failed
    00273     }
    00274   } else if (_wnd.fullscreen) {
    00275     /* restore display? */
    00276     ChangeDisplaySettings(NULL, 0);
    00277   }
    00278 #endif
    00279
    00280   {
    00281     RECT r;
    00282     DWORD style, showstyle;
    00283     int x, y, w, h;
    00284
    00285     showstyle = SW_SHOWNORMAL;
    00286     _wnd.fullscreen = full_screen;
    00287     if (_wnd.fullscreen) {
    00288       style = WS_POPUP;
    00289       SetRect(&r, 0, 0, _wnd.width_org, _wnd.height_org);
    00290     } else {
    00291       style = WS_OVERLAPPEDWINDOW;
    00292       /* On window creation, check if we were in maximize mode before */
    00293       if (_window_maximize) showstyle = SW_SHOWMAXIMIZED;
    00294       SetRect(&r, 0, 0, _wnd.width, _wnd.height);
    00295     }
    00296
    00297 #if !defined(WINCE)
    00298     AdjustWindowRect(&r, style, FALSE);
    00299 #endif
    00300     w = r.right - r.left;
    00301     h = r.bottom - r.top;
    00302     x = (GetSystemMetrics(SM_CXSCREEN) - w) / 2;
    00303     y = (GetSystemMetrics(SM_CYSCREEN) - h) / 2;
    00304
    00305     if (_wnd.main_wnd) {
    00306       ShowWindow(_wnd.main_wnd, SW_SHOWNORMAL); // remove maximize-flag
    00307       SetWindowPos(_wnd.main_wnd, 0, x, y, w, h, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
    00308     } else {
    00309       TCHAR Windowtitle[50];
    00310
    00311       _sntprintf(Windowtitle, lengthof(Windowtitle), _T("OpenTTD %s"), MB_TO_WIDE(_openttd_revision));
    00312
    00313       _wnd.main_wnd = CreateWindow(_T("OTTD"), Windowtitle, style, x, y, w, h, 0, 0, GetModuleHandle(NULL), 0);
    00314       if (_wnd.main_wnd == NULL) usererror("CreateWindow failed");
    00315       ShowWindow(_wnd.main_wnd, showstyle);
    00316     }
    00317   }
    00318
    00319   BlitterFactoryBase::GetCurrentBlitter()->PostResize();
    00320
    00321   GameSizeChanged(); // invalidate all windows, force redraw
    00322   return true; // the request succedded
    00323 }
    00324
    00325 static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
    00326 {
    00327   static uint32 keycode = 0;
    00328   static bool console = false;
    00329
    00330   switch (msg) {
    00331     case WM_CREATE:
    00332       SetTimer(hwnd, TID_POLLMOUSE, MOUSE_POLL_DELAY, (TIMERPROC)TrackMouseTimerProc);
    00333       break;
    00334
    00335     case WM_PAINT: {
    00336       PAINTSTRUCT ps;
    00337       HDC dc, dc2;
    00338       HBITMAP old_bmp;
    00339       HPALETTE old_palette;
    00340
    00341       BeginPaint(hwnd, &ps);
    00342       dc = ps.hdc;
    00343       dc2 = CreateCompatibleDC(dc);
    00344       old_bmp = (HBITMAP)SelectObject(dc2, _wnd.dib_sect);
    00345       old_palette = SelectPalette(dc, _wnd.gdi_palette, FALSE);
    00346
    00347       if (_pal_count_dirty != 0) {
    00348         Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
    00349
    00350         switch (blitter->UsePaletteAnimation()) {
    00351           case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
    00352             UpdatePalette(dc2, _pal_first_dirty, _pal_count_dirty);
    00353             break;
    00354
    00355           case Blitter::PALETTE_ANIMATION_BLITTER:
    00356             blitter->PaletteAnimate(_pal_first_dirty, _pal_count_dirty);
    00357             break;
    00358
    00359           case Blitter::PALETTE_ANIMATION_NONE:
    00360             break;
    00361
    00362           default:
    00363             NOT_REACHED();
    00364         }
    00365         _pal_count_dirty = 0;
    00366       }
    00367
    00368       BitBlt(dc, 0, 0, _wnd.width, _wnd.height, dc2, 0, 0, SRCCOPY);
    00369       SelectPalette(dc, old_palette, TRUE);
    00370       SelectObject(dc2, old_bmp);
    00371       DeleteDC(dc2);
    00372       EndPaint(hwnd, &ps);
    00373       return 0;
    00374     }
    00375
    00376     case WM_PALETTECHANGED:
    00377       if ((HWND)wParam == hwnd) return 0;
    00378       /* FALL THROUGH */
    00379
    00380     case WM_QUERYNEWPALETTE: {
    00381       HDC hDC = GetWindowDC(hwnd);
    00382       HPALETTE hOldPalette = SelectPalette(hDC, _wnd.gdi_palette, FALSE);
    00383       UINT nChanged = RealizePalette(hDC);
    00384
    00385       SelectPalette(hDC, hOldPalette, TRUE);
    00386       ReleaseDC(hwnd, hDC);
    00387       if (nChanged != 0) InvalidateRect(hwnd, NULL, FALSE);
    00388       return 0;
    00389     }
    00390
    00391     case WM_CLOSE:
    00392       HandleExitGameRequest();
    00393       return 0;
    00394
    00395     case WM_DESTROY:
    00396       if (_window_maximize) _cur_resolution = _bck_resolution;
    00397       return 0;
    00398
    00399     case WM_LBUTTONDOWN:
    00400       SetCapture(hwnd);
    00401       _left_button_down = true;
    00402       HandleMouseEvents();
    00403       return 0;
    00404
    00405     case WM_LBUTTONUP:
    00406       ReleaseCapture();
    00407       _left_button_down = false;
    00408       _left_button_clicked = false;
    00409       HandleMouseEvents();
    00410       return 0;
    00411
    00412     case WM_RBUTTONDOWN:
    00413       SetCapture(hwnd);
    00414       _right_button_down = true;
    00415       _right_button_clicked = true;
    00416       HandleMouseEvents();
    00417       return 0;
    00418
    00419     case WM_RBUTTONUP:
    00420       ReleaseCapture();
    00421       _right_button_down = false;
    00422       HandleMouseEvents();
    00423       return 0;
    00424
    00425     case WM_MOUSELEAVE:
    00426       UndrawMouseCursor();
    00427       _cursor.in_window = false;
    00428
    00429       if (!_left_button_down && !_right_button_down) MyShowCursor(true);
    00430       return 0;
    00431
    00432     case WM_MOUSEMOVE: {
    00433       int x = (int16)LOWORD(lParam);
    00434       int y = (int16)HIWORD(lParam);
    00435       POINT pt;
    00436
    00437       /* If the mouse was not in the window and it has moved it means it has
    00438        * come into the window, so start drawing the mouse. Also start
    00439        * tracking the mouse for exiting the window */
    00440       if (!_cursor.in_window) {
    00441         _cursor.in_window = true;
    00442         SetTimer(hwnd, TID_POLLMOUSE, MOUSE_POLL_DELAY, (TIMERPROC)TrackMouseTimerProc);
    00443
    00444         DrawMouseCursor();
    00445       }
    00446
    00447       if (_cursor.fix_at) {
    00448         int dx = x - _cursor.pos.x;
    00449         int dy = y - _cursor.pos.y;
    00450         if (dx != 0 || dy != 0) {
    00451           _cursor.delta.x = dx;
    00452           _cursor.delta.y = dy;
    00453
    00454           pt.x = _cursor.pos.x;
    00455           pt.y = _cursor.pos.y;
    00456
    00457           ClientToScreen(hwnd, &pt);
    00458           SetCursorPos(pt.x, pt.y);
    00459         }
    00460       } else {
    00461         _cursor.delta.x = x - _cursor.pos.x;
    00462         _cursor.delta.y = y - _cursor.pos.y;
    00463         _cursor.pos.x = x;
    00464         _cursor.pos.y = y;
    00465         _cursor.dirty = true;
    00466       }
    00467       MyShowCursor(false);
    00468       HandleMouseEvents();
    00469       return 0;
    00470     }
    00471
    00472 #if !defined(UNICODE)
    00473     case WM_INPUTLANGCHANGE: {
    00474       TCHAR locale[6];
    00475       LCID lcid = GB(lParam, 0, 16);
    00476
    00477       int len = GetLocaleInfo(lcid, LOCALE_IDEFAULTANSICODEPAGE, locale, lengthof(locale));
    00478       if (len != 0) _codepage = _ttoi(locale);
    00479       return 1;
    00480     }
    00481 #endif /* UNICODE */
    00482
    00483     case WM_DEADCHAR:
    00484       console = GB(lParam, 16, 8) == 41;
    00485       return 0;
    00486
    00487     case WM_CHAR: {
    00488       uint scancode = GB(lParam, 16, 8);
    00489       uint charcode = wParam;
    00490
    00491       /* If the console key is a dead-key, we need to press it twice to get a WM_CHAR message.
    00492        * But we then get two WM_CHAR messages, so ignore the first one */
    00493       if (console && scancode == 41) {
    00494         console = false;
    00495         return 0;
    00496       }
    00497
    00498 #if !defined(UNICODE)
    00499       wchar_t w;
    00500       int len = MultiByteToWideChar(_codepage, 0, (char*)&charcode, 1, &w, 1);
    00501       charcode = len == 1 ? w : 0;
    00502 #endif /* UNICODE */
    00503
    00504       /* No matter the keyboard layout, we will map the '~' to the console */
    00505       scancode = scancode == 41 ? (int)WKC_BACKQUOTE : keycode;
    00506       HandleKeypress(GB(charcode, 0, 16) | (scancode << 16));
    00507       return 0;
    00508     }
    00509
    00510     case WM_KEYDOWN: {
    00511       keycode = MapWindowsKey(wParam);
    00512
    00513       /* Silently drop all messages handled by WM_CHAR. */
    00514       MSG msg;
    00515       if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
    00516         if (msg.message == WM_CHAR && GB(lParam, 16, 8) == GB(msg.lParam, 16, 8)) {
    00517           return 0;
    00518         }
    00519       }
    00520
    00521       HandleKeypress(0 | (keycode << 16));
    00522       return 0;
    00523     }
    00524
    00525     case WM_SYSKEYDOWN: // user presses F10 or Alt, both activating the title-menu
    00526       switch (wParam) {
    00527         case VK_RETURN:
    00528         case 'F': // Full Screen on ALT + ENTER/F
    00529           ToggleFullScreen(!_wnd.fullscreen);
    00530           return 0;
    00531
    00532         case VK_MENU: // Just ALT
    00533           return 0; // do nothing
    00534
    00535         case VK_F10: // F10, ignore activation of menu
    00536           HandleKeypress(MapWindowsKey(wParam) << 16);
    00537           return 0;
    00538
    00539         default: // ALT in combination with something else
    00540           HandleKeypress(MapWindowsKey(wParam) << 16);
    00541           break;
    00542       }
    00543       break;
    00544
    00545     case WM_SIZE:
    00546       if (wParam != SIZE_MINIMIZED) {
    00547         /* Set maximized flag when we maximize (obviously), but also when we
    00548          * switched to fullscreen from a maximized state */
    00549         _window_maximize = (wParam == SIZE_MAXIMIZED || (_window_maximize && _fullscreen));
    00550         if (_window_maximize) _bck_resolution = _cur_resolution;
    00551         ClientSizeChanged(LOWORD(lParam), HIWORD(lParam));
    00552       }
    00553       return 0;
    00554
    00555 #if !defined(WINCE)
    00556     case WM_SIZING: {
    00557       RECT *r = (RECT*)lParam;
    00558       RECT r2;
    00559       int w, h;
    00560
    00561       SetRect(&r2, 0, 0, 0, 0);
    00562       AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
    00563
    00564       w = r->right - r->left - (r2.right - r2.left);
    00565       h = r->bottom - r->top - (r2.bottom - r2.top);
    00566       w = max(w, 64);
    00567       h = max(h, 64);
    00568       SetRect(&r2, 0, 0, w, h);
    00569
    00570       AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
    00571       w = r2.right - r2.left;
    00572       h = r2.bottom - r2.top;
    00573
    00574       switch (wParam) {
    00575         case WMSZ_BOTTOM:
    00576           r->bottom = r->top + h;
    00577           break;
    00578
    00579         case WMSZ_BOTTOMLEFT:
    00580           r->bottom = r->top + h;
    00581           r->left = r->right - w;
    00582           break;
    00583
    00584         case WMSZ_BOTTOMRIGHT:
    00585           r->bottom = r->top + h;
    00586           r->right = r->left + w;
    00587           break;
    00588
    00589         case WMSZ_LEFT:
    00590           r->left = r->right - w;
    00591           break;
    00592
    00593         case WMSZ_RIGHT:
    00594           r->right = r->left + w;
    00595           break;
    00596
    00597         case WMSZ_TOP:
    00598           r->top = r->bottom - h;
    00599           break;
    00600
    00601         case WMSZ_TOPLEFT:
    00602           r->top = r->bottom - h;
    00603           r->left = r->right - w;
    00604           break;
    00605
    00606         case WMSZ_TOPRIGHT:
    00607           r->top = r->bottom - h;
    00608           r->right = r->left + w;
    00609           break;
    00610       }
    00611       return TRUE;
    00612     }
    00613 #endif
    00614
    00615 /* needed for wheel */
    00616 #if !defined(WM_MOUSEWHEEL)
    00617 # define WM_MOUSEWHEEL 0x020A
    00618 #endif  /* WM_MOUSEWHEEL */
    00619 #if !defined(GET_WHEEL_DELTA_WPARAM)
    00620 # define GET_WHEEL_DELTA_WPARAM(wparam) ((short)HIWORD(wparam))
    00621 #endif  /* GET_WHEEL_DELTA_WPARAM */
    00622
    00623     case WM_MOUSEWHEEL: {
    00624       int delta = GET_WHEEL_DELTA_WPARAM(wParam);
    00625
    00626       if (delta < 0) {
    00627         _cursor.wheel++;
    00628       } else if (delta > 0) {
    00629         _cursor.wheel--;
    00630       }
    00631       HandleMouseEvents();
    00632       return 0;
    00633     }
    00634
    00635     case WM_SETFOCUS:
    00636       _wnd.has_focus = true;
    00637       break;
    00638
    00639     case WM_KILLFOCUS:
    00640       _wnd.has_focus = false;
    00641       break;
    00642
    00643 #if !defined(WINCE)
    00644     case WM_ACTIVATE: {
    00645       /* Don't do anything if we are closing openttd */
    00646       if (_exit_game) break;
    00647
    00648       bool active = (LOWORD(wParam) != WA_INACTIVE);
    00649       bool minimized = (HIWORD(wParam) != 0);
    00650       if (_wnd.fullscreen) {
    00651         if (active && minimized) {
    00652           /* Restore the game window */
    00653           ShowWindow(hwnd, SW_RESTORE);
    00654           static_cast<VideoDriver_Win32 *>(_video_driver)->MakeWindow(true);
    00655         } else if (!active && !minimized) {
    00656           /* Minimise the window and restore desktop */
    00657           ShowWindow(hwnd, SW_MINIMIZE);
    00658           ChangeDisplaySettings(NULL, 0);
    00659         }
    00660       }
    00661       break;
    00662     }
    00663 #endif
    00664   }
    00665
    00666   return DefWindowProc(hwnd, msg, wParam, lParam);
    00667 }
    00668
    00669 static void RegisterWndClass()
    00670 {
    00671   static bool registered = false;
    00672
    00673   if (!registered) {
    00674     HINSTANCE hinst = GetModuleHandle(NULL);
    00675     WNDCLASS wnd = {
    00676       0,
    00677       WndProcGdi,
    00678       0,
    00679       0,
    00680       hinst,
    00681       LoadIcon(hinst, MAKEINTRESOURCE(100)),
    00682       LoadCursor(NULL, IDC_ARROW),
    00683       0,
    00684       0,
    00685       _T("OTTD")
    00686     };
    00687
    00688     registered = true;
    00689     if (!RegisterClass(&wnd)) usererror("RegisterClass failed");
    00690   }
    00691 }
    00692
    00693 static bool AllocateDibSection(int w, int h)
    00694 {
    00695   BITMAPINFO *bi;
    00696   HDC dc;
    00697   int bpp = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
    00698
    00699   w = max(w, 64);
    00700   h = max(h, 64);
    00701
    00702   if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");
    00703
    00704   if (w == _screen.width && h == _screen.height) return false;
    00705
    00706   _screen.width = w;
    00707   _screen.pitch = (bpp == 8) ? Align(w, 4) : w;
    00708   _screen.height = h;
    00709   bi = (BITMAPINFO*)alloca(sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256);
    00710   memset(bi, 0, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256);
    00711   bi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    00712
    00713   bi->bmiHeader.biWidth = _wnd.width = w;
    00714   bi->bmiHeader.biHeight = -(_wnd.height = h);
    00715
    00716   bi->bmiHeader.biPlanes = 1;
    00717   bi->bmiHeader.biBitCount = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
    00718   bi->bmiHeader.biCompression = BI_RGB;
    00719
    00720   if (_wnd.dib_sect) DeleteObject(_wnd.dib_sect);
    00721
    00722   dc = GetDC(0);
    00723   _wnd.dib_sect = CreateDIBSection(dc, bi, DIB_RGB_COLORS, (VOID**)&_wnd.buffer_bits, NULL, 0);
    00724   if (_wnd.dib_sect == NULL) usererror("CreateDIBSection failed");
    00725   ReleaseDC(0, dc);
    00726
    00727   return true;
    00728 }
    00729
    00730 static const Dimension default_resolutions[] = {
    00731   {  640,  480 },
    00732   {  800,  600 },
    00733   { 1024,  768 },
    00734   { 1152,  864 },
    00735   { 1280,  800 },
    00736   { 1280,  960 },
    00737   { 1280, 1024 },
    00738   { 1400, 1050 },
    00739   { 1600, 1200 },
    00740   { 1680, 1050 },
    00741   { 1920, 1200 }
    00742 };
    00743
    00744 static void FindResolutions()
    00745 {
    00746   uint n = 0;
    00747 #if defined(WINCE)
    00748   /* EnumDisplaySettingsW is only supported in CE 4.2+
    00749    * XXX -- One might argue that we assume 4.2+ on every system. Then we can use this function safely */
    00750 #else
    00751   uint i;
    00752   DEVMODEA dm;
    00753
    00754   /* XXX - EnumDisplaySettingsW crashes with unicows.dll on Windows95
    00755    * Doesn't really matter since we don't pass a string anyways, but still
    00756    * a letdown */
    00757   for (i = 0; EnumDisplaySettingsA(NULL, i, &dm) != 0; i++) {
    00758     if (dm.dmBitsPerPel == BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() &&
    00759         dm.dmPelsWidth >= 640 && dm.dmPelsHeight >= 480) {
    00760       uint j;
    00761
    00762       for (j = 0; j < n; j++) {
    00763         if (_resolutions[j].width == dm.dmPelsWidth && _resolutions[j].height == dm.dmPelsHeight) break;
    00764       }
    00765
    00766       /* In the previous loop we have checked already existing/added resolutions if
    00767        * they are the same as the new ones. If this is not the case (j == n); we have
    00768        * looped all and found none, add the new one to the list. If we have reached the
    00769        * maximum amount of resolutions, then quit querying the display */
    00770       if (j == n) {
    00771         _resolutions[j].width  = dm.dmPelsWidth;
    00772         _resolutions[j].height = dm.dmPelsHeight;
    00773         if (++n == lengthof(_resolutions)) break;
    00774       }
    00775     }
    00776   }
    00777 #endif
    00778
    00779   /* We have found no resolutions, show the default list */
    00780   if (n == 0) {
    00781     memcpy(_resolutions, default_resolutions, sizeof(default_resolutions));
    00782     n = lengthof(default_resolutions);
    00783   }
    00784
    00785   _num_resolutions = n;
    00786   SortResolutions(_num_resolutions);
    00787 }
    00788
    00789 static FVideoDriver_Win32 iFVideoDriver_Win32;
    00790
    00791 const char *VideoDriver_Win32::Start(const char * const *parm)
    00792 {
    00793   memset(&_wnd, 0, sizeof(_wnd));
    00794
    00795   RegisterWndClass();
    00796
    00797   MakePalette();
    00798
    00799   FindResolutions();
    00800
    00801   DEBUG(driver, 2, "Resolution for display: %ux%u", _cur_resolution.width, _cur_resolution.height);
    00802
    00803   /* fullscreen uses those */
    00804   _wnd.width_org  = _cur_resolution.width;
    00805   _wnd.height_org = _cur_resolution.height;
    00806
    00807   AllocateDibSection(_cur_resolution.width, _cur_resolution.height);
    00808   this->MakeWindow(_fullscreen);
    00809
    00810   MarkWholeScreenDirty();
    00811
    00812   return NULL;
    00813 }
    00814
    00815 void VideoDriver_Win32::Stop()
    00816 {
    00817   DeleteObject(_wnd.gdi_palette);
    00818   DeleteObject(_wnd.dib_sect);
    00819   DestroyWindow(_wnd.main_wnd);
    00820
    00821 #if !defined(WINCE)
    00822   if (_wnd.fullscreen) ChangeDisplaySettings(NULL, 0);
    00823 #endif
    00824   MyShowCursor(true);
    00825 }
    00826
    00827 void VideoDriver_Win32::MakeDirty(int left, int top, int width, int height)
    00828 {
    00829   RECT r = { left, top, left + width, top + height };
    00830
    00831   InvalidateRect(_wnd.main_wnd, &r, FALSE);
    00832 }
    00833
    00834 static void CheckPaletteAnim()
    00835 {
    00836   if (_pal_count_dirty == 0) return;
    00837
    00838   InvalidateRect(_wnd.main_wnd, NULL, FALSE);
    00839 }
    00840
    00841 void VideoDriver_Win32::MainLoop()
    00842 {
    00843   MSG mesg;
    00844   uint32 cur_ticks = GetTickCount();
    00845   uint32 last_cur_ticks = cur_ticks;
    00846   uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
    00847
    00848   _wnd.running = true;
    00849
    00850   for (;;) {
    00851     uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
    00852
    00853     while (PeekMessage(&mesg, NULL, 0, 0, PM_REMOVE)) {
    00854       InteractiveRandom(); // randomness
    00855       TranslateMessage(&mesg);
    00856       DispatchMessage(&mesg);
    00857     }
    00858     if (_exit_game) return;
    00859
    00860 #if defined(_DEBUG)
    00861     if (_wnd.has_focus && GetAsyncKeyState(VK_SHIFT) < 0 &&
    00862 #else
    00863     /* Speed up using TAB, but disable for ALT+TAB of course */
    00864     if (_wnd.has_focus && GetAsyncKeyState(VK_TAB) < 0 && GetAsyncKeyState(VK_MENU) >= 0 &&
    00865 #endif
    00866         !_networking && _game_mode != GM_MENU) {
    00867       _fast_forward |= 2;
    00868     } else if (_fast_forward & 2) {
    00869       _fast_forward = 0;
    00870     }
    00871
    00872     cur_ticks = GetTickCount();
    00873     if (cur_ticks >= next_tick || (_fast_forward && !_pause_mode) || cur_ticks < prev_cur_ticks) {
    00874       _realtime_tick += cur_ticks - last_cur_ticks;
    00875       last_cur_ticks = cur_ticks;
    00876       next_tick = cur_ticks + MILLISECONDS_PER_TICK;
    00877
    00878       bool old_ctrl_pressed = _ctrl_pressed;
    00879
    00880       _ctrl_pressed = _wnd.has_focus && GetAsyncKeyState(VK_CONTROL)<0;
    00881       _shift_pressed = _wnd.has_focus && GetAsyncKeyState(VK_SHIFT)<0;
    00882
    00883       /* determine which directional keys are down */
    00884       if (_wnd.has_focus) {
    00885         _dirkeys =
    00886           (GetAsyncKeyState(VK_LEFT) < 0 ? 1 : 0) +
    00887           (GetAsyncKeyState(VK_UP) < 0 ? 2 : 0) +
    00888           (GetAsyncKeyState(VK_RIGHT) < 0 ? 4 : 0) +
    00889           (GetAsyncKeyState(VK_DOWN) < 0 ? 8 : 0);
    00890       } else {
    00891         _dirkeys = 0;
    00892       }
    00893
    00894       if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
    00895
    00896       GameLoop();
    00897
    00898       if (_force_full_redraw) MarkWholeScreenDirty();
    00899
    00900 #if !defined(WINCE)
    00901       GdiFlush();
    00902 #endif
    00903       _screen.dst_ptr = _wnd.buffer_bits;
    00904       UpdateWindows();
    00905       CheckPaletteAnim();
    00906     } else {
    00907       Sleep(1);
    00908 #if !defined(WINCE)
    00909       GdiFlush();
    00910 #endif
    00911       _screen.dst_ptr = _wnd.buffer_bits;
    00912       NetworkDrawChatMessage();
    00913       DrawMouseCursor();
    00914     }
    00915   }
    00916 }
    00917
    00918 bool VideoDriver_Win32::ChangeResolution(int w, int h)
    00919 {
    00920   _wnd.width = _wnd.width_org = w;
    00921   _wnd.height = _wnd.height_org = h;
    00922
    00923   return this->MakeWindow(_fullscreen); // _wnd.fullscreen screws up ingame resolution switching
    00924 }
    00925
    00926 bool VideoDriver_Win32::ToggleFullscreen(bool full_screen)
    00927 {
    00928   return this->MakeWindow(full_screen);
    00929 }