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