win32_v.cpp

Go to the documentation of this file.
00001 /* $Id: win32_v.cpp 24229 2012-05-12 07:37:14Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
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     /* restore the resolution */
00300     _wnd.width = _bck_resolution.width;
00301     _wnd.height = _bck_resolution.height;
00302   }
00303 #endif
00304 
00305   {
00306     RECT r;
00307     DWORD style, showstyle;
00308     int x, y, w, h;
00309 
00310     showstyle = SW_SHOWNORMAL;
00311     _wnd.fullscreen = full_screen;
00312     if (_wnd.fullscreen) {
00313       style = WS_POPUP;
00314       SetRect(&r, 0, 0, _wnd.width_org, _wnd.height_org);
00315     } else {
00316       style = WS_OVERLAPPEDWINDOW;
00317       /* On window creation, check if we were in maximize mode before */
00318       if (_window_maximize) showstyle = SW_SHOWMAXIMIZED;
00319       SetRect(&r, 0, 0, _wnd.width, _wnd.height);
00320     }
00321 
00322 #if !defined(WINCE)
00323     AdjustWindowRect(&r, style, FALSE);
00324 #endif
00325 
00326     if (_wnd.main_wnd == NULL) {
00327       w = r.right - r.left;
00328       h = r.bottom - r.top;
00329       x = (GetSystemMetrics(SM_CXSCREEN) - w) / 2;
00330       y = (GetSystemMetrics(SM_CYSCREEN) - h) / 2;
00331 
00332       TCHAR Windowtitle[50];
00333 
00334       _sntprintf(Windowtitle, lengthof(Windowtitle), _T("OpenTTD %s"), MB_TO_WIDE(_openttd_revision));
00335 
00336       _wnd.main_wnd = CreateWindow(_T("OTTD"), Windowtitle, style, x, y, w, h, 0, 0, GetModuleHandle(NULL), 0);
00337       if (_wnd.main_wnd == NULL) usererror("CreateWindow failed");
00338       ShowWindow(_wnd.main_wnd, showstyle);
00339     }
00340   }
00341 
00342   BlitterFactoryBase::GetCurrentBlitter()->PostResize();
00343 
00344   GameSizeChanged(); // invalidate all windows, force redraw
00345   return true; // the request succedded
00346 }
00347 
00349 static void PaintWindow(HDC dc)
00350 {
00351   HDC dc2 = CreateCompatibleDC(dc);
00352   HBITMAP old_bmp = (HBITMAP)SelectObject(dc2, _wnd.dib_sect);
00353   HPALETTE old_palette = SelectPalette(dc, _wnd.gdi_palette, FALSE);
00354 
00355   if (_cur_palette.count_dirty != 0) {
00356     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00357 
00358     switch (blitter->UsePaletteAnimation()) {
00359       case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
00360         UpdatePalette(dc2, _local_palette.first_dirty, _local_palette.count_dirty);
00361         break;
00362 
00363       case Blitter::PALETTE_ANIMATION_BLITTER:
00364         blitter->PaletteAnimate(_local_palette);
00365         break;
00366 
00367       case Blitter::PALETTE_ANIMATION_NONE:
00368         break;
00369 
00370       default:
00371         NOT_REACHED();
00372     }
00373     _cur_palette.count_dirty = 0;
00374   }
00375 
00376   BitBlt(dc, 0, 0, _wnd.width, _wnd.height, dc2, 0, 0, SRCCOPY);
00377   SelectPalette(dc, old_palette, TRUE);
00378   SelectObject(dc2, old_bmp);
00379   DeleteDC(dc2);
00380 }
00381 
00382 static void PaintWindowThread(void *)
00383 {
00384   /* First tell the main thread we're started */
00385   _draw_mutex->BeginCritical();
00386   _draw_mutex->SendSignal();
00387 
00388   /* Do our best to make sure the main thread is the one that
00389    * gets the signal, and not our wait below. */
00390   Sleep(0);
00391 
00392   /* Now wait for the first thing to draw! */
00393   _draw_mutex->WaitForSignal();
00394 
00395   while (_draw_continue) {
00396     /* Convert update region from logical to device coordinates. */
00397     POINT pt = {0, 0};
00398     ClientToScreen(_wnd.main_wnd, &pt);
00399     OffsetRect(&_wnd.update_rect, pt.x, pt.y);
00400 
00401     /* Create a device context that is clipped to the region we need to draw.
00402      * GetDCEx 'consumes' the update region, so we may not destroy it ourself. */
00403     HRGN rgn = CreateRectRgnIndirect(&_wnd.update_rect);
00404     HDC dc = GetDCEx(_wnd.main_wnd, rgn, DCX_CLIPSIBLINGS | DCX_CLIPCHILDREN | DCX_INTERSECTRGN);
00405 
00406     PaintWindow(dc);
00407 
00408     /* Clear update rect. */
00409     SetRectEmpty(&_wnd.update_rect);
00410     ReleaseDC(_wnd.main_wnd, dc);
00411 
00412     /* Flush GDI buffer to ensure drawing here doesn't conflict with any GDI usage in the main WndProc. */
00413     GdiFlush();
00414 
00415     _draw_mutex->WaitForSignal();
00416   }
00417 
00418   _draw_mutex->EndCritical();
00419   _draw_thread->Exit();
00420 }
00421 
00422 static LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
00423 {
00424   static uint32 keycode = 0;
00425   static bool console = false;
00426   static bool in_sizemove = false;
00427 
00428   switch (msg) {
00429     case WM_CREATE:
00430       SetTimer(hwnd, TID_POLLMOUSE, MOUSE_POLL_DELAY, (TIMERPROC)TrackMouseTimerProc);
00431       break;
00432 
00433     case WM_ENTERSIZEMOVE:
00434       in_sizemove = true;
00435       break;
00436 
00437     case WM_EXITSIZEMOVE:
00438       in_sizemove = false;
00439       break;
00440 
00441     case WM_PAINT:
00442       if (!in_sizemove && _draw_mutex != NULL && !HasModalProgress()) {
00443         /* Get the union of the old update rect and the new update rect. */
00444         RECT r;
00445         GetUpdateRect(hwnd, &r, FALSE);
00446         UnionRect(&_wnd.update_rect, &_wnd.update_rect, &r);
00447 
00448         /* Mark the window as updated, otherwise Windows would send more WM_PAINT messages. */
00449         ValidateRect(hwnd, NULL);
00450         _draw_mutex->SendSignal();
00451       } else {
00452         PAINTSTRUCT ps;
00453 
00454         BeginPaint(hwnd, &ps);
00455         PaintWindow(ps.hdc);
00456         EndPaint(hwnd, &ps);
00457       }
00458       return 0;
00459 
00460     case WM_PALETTECHANGED:
00461       if ((HWND)wParam == hwnd) return 0;
00462       /* FALL THROUGH */
00463 
00464     case WM_QUERYNEWPALETTE: {
00465       HDC hDC = GetWindowDC(hwnd);
00466       HPALETTE hOldPalette = SelectPalette(hDC, _wnd.gdi_palette, FALSE);
00467       UINT nChanged = RealizePalette(hDC);
00468 
00469       SelectPalette(hDC, hOldPalette, TRUE);
00470       ReleaseDC(hwnd, hDC);
00471       if (nChanged != 0) InvalidateRect(hwnd, NULL, FALSE);
00472       return 0;
00473     }
00474 
00475     case WM_CLOSE:
00476       HandleExitGameRequest();
00477       return 0;
00478 
00479     case WM_DESTROY:
00480       if (_window_maximize) _cur_resolution = _bck_resolution;
00481       return 0;
00482 
00483     case WM_LBUTTONDOWN:
00484       SetCapture(hwnd);
00485       _left_button_down = true;
00486       HandleMouseEvents();
00487       return 0;
00488 
00489     case WM_LBUTTONUP:
00490       ReleaseCapture();
00491       _left_button_down = false;
00492       _left_button_clicked = false;
00493       HandleMouseEvents();
00494       return 0;
00495 
00496     case WM_RBUTTONDOWN:
00497       SetCapture(hwnd);
00498       _right_button_down = true;
00499       _right_button_clicked = true;
00500       HandleMouseEvents();
00501       return 0;
00502 
00503     case WM_RBUTTONUP:
00504       ReleaseCapture();
00505       _right_button_down = false;
00506       HandleMouseEvents();
00507       return 0;
00508 
00509     case WM_MOUSELEAVE:
00510       UndrawMouseCursor();
00511       _cursor.in_window = false;
00512 
00513       if (!_left_button_down && !_right_button_down) MyShowCursor(true);
00514       return 0;
00515 
00516     case WM_MOUSEMOVE: {
00517       int x = (int16)LOWORD(lParam);
00518       int y = (int16)HIWORD(lParam);
00519       POINT pt;
00520 
00521       /* If the mouse was not in the window and it has moved it means it has
00522        * come into the window, so start drawing the mouse. Also start
00523        * tracking the mouse for exiting the window */
00524       if (!_cursor.in_window) {
00525         _cursor.in_window = true;
00526         SetTimer(hwnd, TID_POLLMOUSE, MOUSE_POLL_DELAY, (TIMERPROC)TrackMouseTimerProc);
00527 
00528         DrawMouseCursor();
00529       }
00530 
00531       if (_cursor.fix_at) {
00532         int dx = x - _cursor.pos.x;
00533         int dy = y - _cursor.pos.y;
00534         if (dx != 0 || dy != 0) {
00535           _cursor.delta.x = dx;
00536           _cursor.delta.y = dy;
00537 
00538           pt.x = _cursor.pos.x;
00539           pt.y = _cursor.pos.y;
00540 
00541           ClientToScreen(hwnd, &pt);
00542           SetCursorPos(pt.x, pt.y);
00543         }
00544       } else {
00545         _cursor.delta.x = x - _cursor.pos.x;
00546         _cursor.delta.y = y - _cursor.pos.y;
00547         _cursor.pos.x = x;
00548         _cursor.pos.y = y;
00549         _cursor.dirty = true;
00550       }
00551       MyShowCursor(false);
00552       HandleMouseEvents();
00553       return 0;
00554     }
00555 
00556 #if !defined(UNICODE)
00557     case WM_INPUTLANGCHANGE: {
00558       TCHAR locale[6];
00559       LCID lcid = GB(lParam, 0, 16);
00560 
00561       int len = GetLocaleInfo(lcid, LOCALE_IDEFAULTANSICODEPAGE, locale, lengthof(locale));
00562       if (len != 0) _codepage = _ttoi(locale);
00563       return 1;
00564     }
00565 #endif /* UNICODE */
00566 
00567     case WM_DEADCHAR:
00568       console = GB(lParam, 16, 8) == 41;
00569       return 0;
00570 
00571     case WM_CHAR: {
00572       uint scancode = GB(lParam, 16, 8);
00573       uint charcode = wParam;
00574 
00575       /* If the console key is a dead-key, we need to press it twice to get a WM_CHAR message.
00576        * But we then get two WM_CHAR messages, so ignore the first one */
00577       if (console && scancode == 41) {
00578         console = false;
00579         return 0;
00580       }
00581 
00582 #if !defined(UNICODE)
00583       wchar_t w;
00584       int len = MultiByteToWideChar(_codepage, 0, (char*)&charcode, 1, &w, 1);
00585       charcode = len == 1 ? w : 0;
00586 #endif /* UNICODE */
00587 
00588       /* No matter the keyboard layout, we will map the '~' to the console */
00589       scancode = scancode == 41 ? (int)WKC_BACKQUOTE : keycode;
00590       HandleKeypress(GB(charcode, 0, 16) | (scancode << 16));
00591       return 0;
00592     }
00593 
00594     case WM_KEYDOWN: {
00595       keycode = MapWindowsKey(wParam);
00596 
00597       /* Silently drop all messages handled by WM_CHAR. */
00598       MSG msg;
00599       if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
00600         if (msg.message == WM_CHAR && GB(lParam, 16, 8) == GB(msg.lParam, 16, 8)) {
00601           return 0;
00602         }
00603       }
00604 
00605       HandleKeypress(0 | (keycode << 16));
00606       return 0;
00607     }
00608 
00609     case WM_SYSKEYDOWN: // user presses F10 or Alt, both activating the title-menu
00610       switch (wParam) {
00611         case VK_RETURN:
00612         case 'F': // Full Screen on ALT + ENTER/F
00613           ToggleFullScreen(!_wnd.fullscreen);
00614           return 0;
00615 
00616         case VK_MENU: // Just ALT
00617           return 0; // do nothing
00618 
00619         case VK_F10: // F10, ignore activation of menu
00620           HandleKeypress(MapWindowsKey(wParam) << 16);
00621           return 0;
00622 
00623         default: // ALT in combination with something else
00624           HandleKeypress(MapWindowsKey(wParam) << 16);
00625           break;
00626       }
00627       break;
00628 
00629     case WM_SIZE:
00630       if (wParam != SIZE_MINIMIZED) {
00631         /* Set maximized flag when we maximize (obviously), but also when we
00632          * switched to fullscreen from a maximized state */
00633         _window_maximize = (wParam == SIZE_MAXIMIZED || (_window_maximize && _fullscreen));
00634         if (_window_maximize || _fullscreen) _bck_resolution = _cur_resolution;
00635         ClientSizeChanged(LOWORD(lParam), HIWORD(lParam));
00636       }
00637       return 0;
00638 
00639 #if !defined(WINCE)
00640     case WM_SIZING: {
00641       RECT *r = (RECT*)lParam;
00642       RECT r2;
00643       int w, h;
00644 
00645       SetRect(&r2, 0, 0, 0, 0);
00646       AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
00647 
00648       w = r->right - r->left - (r2.right - r2.left);
00649       h = r->bottom - r->top - (r2.bottom - r2.top);
00650       w = max(w, 64);
00651       h = max(h, 64);
00652       SetRect(&r2, 0, 0, w, h);
00653 
00654       AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
00655       w = r2.right - r2.left;
00656       h = r2.bottom - r2.top;
00657 
00658       switch (wParam) {
00659         case WMSZ_BOTTOM:
00660           r->bottom = r->top + h;
00661           break;
00662 
00663         case WMSZ_BOTTOMLEFT:
00664           r->bottom = r->top + h;
00665           r->left = r->right - w;
00666           break;
00667 
00668         case WMSZ_BOTTOMRIGHT:
00669           r->bottom = r->top + h;
00670           r->right = r->left + w;
00671           break;
00672 
00673         case WMSZ_LEFT:
00674           r->left = r->right - w;
00675           break;
00676 
00677         case WMSZ_RIGHT:
00678           r->right = r->left + w;
00679           break;
00680 
00681         case WMSZ_TOP:
00682           r->top = r->bottom - h;
00683           break;
00684 
00685         case WMSZ_TOPLEFT:
00686           r->top = r->bottom - h;
00687           r->left = r->right - w;
00688           break;
00689 
00690         case WMSZ_TOPRIGHT:
00691           r->top = r->bottom - h;
00692           r->right = r->left + w;
00693           break;
00694       }
00695       return TRUE;
00696     }
00697 #endif
00698 
00699 /* needed for wheel */
00700 #if !defined(WM_MOUSEWHEEL)
00701 # define WM_MOUSEWHEEL 0x020A
00702 #endif  /* WM_MOUSEWHEEL */
00703 #if !defined(GET_WHEEL_DELTA_WPARAM)
00704 # define GET_WHEEL_DELTA_WPARAM(wparam) ((short)HIWORD(wparam))
00705 #endif  /* GET_WHEEL_DELTA_WPARAM */
00706 
00707     case WM_MOUSEWHEEL: {
00708       int delta = GET_WHEEL_DELTA_WPARAM(wParam);
00709 
00710       if (delta < 0) {
00711         _cursor.wheel++;
00712       } else if (delta > 0) {
00713         _cursor.wheel--;
00714       }
00715       HandleMouseEvents();
00716       return 0;
00717     }
00718 
00719     case WM_SETFOCUS:
00720       _wnd.has_focus = true;
00721       break;
00722 
00723     case WM_KILLFOCUS:
00724       _wnd.has_focus = false;
00725       break;
00726 
00727 #if !defined(WINCE)
00728     case WM_ACTIVATE: {
00729       /* Don't do anything if we are closing openttd */
00730       if (_exit_game) break;
00731 
00732       bool active = (LOWORD(wParam) != WA_INACTIVE);
00733       bool minimized = (HIWORD(wParam) != 0);
00734       if (_wnd.fullscreen) {
00735         if (active && minimized) {
00736           /* Restore the game window */
00737           ShowWindow(hwnd, SW_RESTORE);
00738           static_cast<VideoDriver_Win32 *>(_video_driver)->MakeWindow(true);
00739         } else if (!active && !minimized) {
00740           /* Minimise the window and restore desktop */
00741           ShowWindow(hwnd, SW_MINIMIZE);
00742           ChangeDisplaySettings(NULL, 0);
00743         }
00744       }
00745       break;
00746     }
00747 #endif
00748   }
00749 
00750   return DefWindowProc(hwnd, msg, wParam, lParam);
00751 }
00752 
00753 static void RegisterWndClass()
00754 {
00755   static bool registered = false;
00756 
00757   if (!registered) {
00758     HINSTANCE hinst = GetModuleHandle(NULL);
00759     WNDCLASS wnd = {
00760       CS_OWNDC,
00761       WndProcGdi,
00762       0,
00763       0,
00764       hinst,
00765       LoadIcon(hinst, MAKEINTRESOURCE(100)),
00766       LoadCursor(NULL, IDC_ARROW),
00767       0,
00768       0,
00769       _T("OTTD")
00770     };
00771 
00772     registered = true;
00773     if (!RegisterClass(&wnd)) usererror("RegisterClass failed");
00774   }
00775 }
00776 
00777 static bool AllocateDibSection(int w, int h, bool force)
00778 {
00779   BITMAPINFO *bi;
00780   HDC dc;
00781   int bpp = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
00782 
00783   w = max(w, 64);
00784   h = max(h, 64);
00785 
00786   if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");
00787 
00788   if (!force && w == _screen.width && h == _screen.height) return false;
00789 
00790   _screen.width = w;
00791   _screen.pitch = (bpp == 8) ? Align(w, 4) : w;
00792   _screen.height = h;
00793   bi = (BITMAPINFO*)alloca(sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256);
00794   memset(bi, 0, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256);
00795   bi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
00796 
00797   bi->bmiHeader.biWidth = _wnd.width = w;
00798   bi->bmiHeader.biHeight = -(_wnd.height = h);
00799 
00800   bi->bmiHeader.biPlanes = 1;
00801   bi->bmiHeader.biBitCount = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
00802   bi->bmiHeader.biCompression = BI_RGB;
00803 
00804   if (_wnd.dib_sect) DeleteObject(_wnd.dib_sect);
00805 
00806   dc = GetDC(0);
00807   _wnd.dib_sect = CreateDIBSection(dc, bi, DIB_RGB_COLORS, (VOID**)&_wnd.buffer_bits, NULL, 0);
00808   if (_wnd.dib_sect == NULL) usererror("CreateDIBSection failed");
00809   ReleaseDC(0, dc);
00810 
00811   return true;
00812 }
00813 
00814 static const Dimension default_resolutions[] = {
00815   {  640,  480 },
00816   {  800,  600 },
00817   { 1024,  768 },
00818   { 1152,  864 },
00819   { 1280,  800 },
00820   { 1280,  960 },
00821   { 1280, 1024 },
00822   { 1400, 1050 },
00823   { 1600, 1200 },
00824   { 1680, 1050 },
00825   { 1920, 1200 }
00826 };
00827 
00828 static void FindResolutions()
00829 {
00830   uint n = 0;
00831 #if defined(WINCE)
00832   /* EnumDisplaySettingsW is only supported in CE 4.2+
00833    * XXX -- One might argue that we assume 4.2+ on every system. Then we can use this function safely */
00834 #else
00835   uint i;
00836   DEVMODEA dm;
00837 
00838   /* XXX - EnumDisplaySettingsW crashes with unicows.dll on Windows95
00839    * Doesn't really matter since we don't pass a string anyways, but still
00840    * a letdown */
00841   for (i = 0; EnumDisplaySettingsA(NULL, i, &dm) != 0; i++) {
00842     if (dm.dmBitsPerPel == BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() &&
00843         dm.dmPelsWidth >= 640 && dm.dmPelsHeight >= 480) {
00844       uint j;
00845 
00846       for (j = 0; j < n; j++) {
00847         if (_resolutions[j].width == dm.dmPelsWidth && _resolutions[j].height == dm.dmPelsHeight) break;
00848       }
00849 
00850       /* In the previous loop we have checked already existing/added resolutions if
00851        * they are the same as the new ones. If this is not the case (j == n); we have
00852        * looped all and found none, add the new one to the list. If we have reached the
00853        * maximum amount of resolutions, then quit querying the display */
00854       if (j == n) {
00855         _resolutions[j].width  = dm.dmPelsWidth;
00856         _resolutions[j].height = dm.dmPelsHeight;
00857         if (++n == lengthof(_resolutions)) break;
00858       }
00859     }
00860   }
00861 #endif
00862 
00863   /* We have found no resolutions, show the default list */
00864   if (n == 0) {
00865     memcpy(_resolutions, default_resolutions, sizeof(default_resolutions));
00866     n = lengthof(default_resolutions);
00867   }
00868 
00869   _num_resolutions = n;
00870   SortResolutions(_num_resolutions);
00871 }
00872 
00873 static FVideoDriver_Win32 iFVideoDriver_Win32;
00874 
00875 const char *VideoDriver_Win32::Start(const char * const *parm)
00876 {
00877   memset(&_wnd, 0, sizeof(_wnd));
00878 
00879   RegisterWndClass();
00880 
00881   MakePalette();
00882 
00883   FindResolutions();
00884 
00885   DEBUG(driver, 2, "Resolution for display: %ux%u", _cur_resolution.width, _cur_resolution.height);
00886 
00887   /* fullscreen uses those */
00888   _wnd.width_org  = _cur_resolution.width;
00889   _wnd.height_org = _cur_resolution.height;
00890 
00891   AllocateDibSection(_cur_resolution.width, _cur_resolution.height);
00892   this->MakeWindow(_fullscreen);
00893 
00894   MarkWholeScreenDirty();
00895 
00896   _draw_threaded = GetDriverParam(parm, "no_threads") == NULL && GetDriverParam(parm, "no_thread") == NULL && GetCPUCoreCount() > 1;
00897 
00898   return NULL;
00899 }
00900 
00901 void VideoDriver_Win32::Stop()
00902 {
00903   DeleteObject(_wnd.gdi_palette);
00904   DeleteObject(_wnd.dib_sect);
00905   DestroyWindow(_wnd.main_wnd);
00906 
00907 #if !defined(WINCE)
00908   if (_wnd.fullscreen) ChangeDisplaySettings(NULL, 0);
00909 #endif
00910   MyShowCursor(true);
00911 }
00912 
00913 void VideoDriver_Win32::MakeDirty(int left, int top, int width, int height)
00914 {
00915   RECT r = { left, top, left + width, top + height };
00916 
00917   InvalidateRect(_wnd.main_wnd, &r, FALSE);
00918 }
00919 
00920 static void CheckPaletteAnim()
00921 {
00922   if (_cur_palette.count_dirty == 0) return;
00923 
00924   _local_palette = _cur_palette;
00925   InvalidateRect(_wnd.main_wnd, NULL, FALSE);
00926 }
00927 
00928 void VideoDriver_Win32::MainLoop()
00929 {
00930   MSG mesg;
00931   uint32 cur_ticks = GetTickCount();
00932   uint32 last_cur_ticks = cur_ticks;
00933   uint32 next_tick = cur_ticks + MILLISECONDS_PER_TICK;
00934 
00935   if (_draw_threaded) {
00936     /* Initialise the mutex first, because that's the thing we *need*
00937      * directly in the newly created thread. */
00938     _draw_mutex = ThreadMutex::New();
00939     if (_draw_mutex == NULL) {
00940       _draw_threaded = false;
00941     } else {
00942       _draw_mutex->BeginCritical();
00943       _draw_continue = true;
00944 
00945       _draw_threaded = ThreadObject::New(&PaintWindowThread, NULL, &_draw_thread);
00946 
00947       /* Free the mutex if we won't be able to use it. */
00948       if (!_draw_threaded) {
00949         _draw_mutex->EndCritical();
00950         delete _draw_mutex;
00951         _draw_mutex = NULL;
00952       } else {
00953         DEBUG(driver, 1, "Threaded drawing enabled");
00954 
00955         /* Wait till the draw mutex has started itself. */
00956         _draw_mutex->WaitForSignal();
00957       }
00958     }
00959   }
00960 
00961   _wnd.running = true;
00962 
00963   CheckPaletteAnim();
00964   for (;;) {
00965     uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
00966 
00967     while (PeekMessage(&mesg, NULL, 0, 0, PM_REMOVE)) {
00968       InteractiveRandom(); // randomness
00969       TranslateMessage(&mesg);
00970       DispatchMessage(&mesg);
00971     }
00972     if (_exit_game) return;
00973 
00974 #if defined(_DEBUG)
00975     if (_wnd.has_focus && GetAsyncKeyState(VK_SHIFT) < 0 &&
00976 #else
00977     /* Speed up using TAB, but disable for ALT+TAB of course */
00978     if (_wnd.has_focus && GetAsyncKeyState(VK_TAB) < 0 && GetAsyncKeyState(VK_MENU) >= 0 &&
00979 #endif
00980         !_networking && _game_mode != GM_MENU) {
00981       _fast_forward |= 2;
00982     } else if (_fast_forward & 2) {
00983       _fast_forward = 0;
00984     }
00985 
00986     cur_ticks = GetTickCount();
00987     if (cur_ticks >= next_tick || (_fast_forward && !_pause_mode) || cur_ticks < prev_cur_ticks) {
00988       _realtime_tick += cur_ticks - last_cur_ticks;
00989       last_cur_ticks = cur_ticks;
00990       next_tick = cur_ticks + MILLISECONDS_PER_TICK;
00991 
00992       bool old_ctrl_pressed = _ctrl_pressed;
00993 
00994       _ctrl_pressed = _wnd.has_focus && GetAsyncKeyState(VK_CONTROL)<0;
00995       _shift_pressed = _wnd.has_focus && GetAsyncKeyState(VK_SHIFT)<0;
00996 
00997       /* determine which directional keys are down */
00998       if (_wnd.has_focus) {
00999         _dirkeys =
01000           (GetAsyncKeyState(VK_LEFT) < 0 ? 1 : 0) +
01001           (GetAsyncKeyState(VK_UP) < 0 ? 2 : 0) +
01002           (GetAsyncKeyState(VK_RIGHT) < 0 ? 4 : 0) +
01003           (GetAsyncKeyState(VK_DOWN) < 0 ? 8 : 0);
01004       } else {
01005         _dirkeys = 0;
01006       }
01007 
01008       if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
01009 
01010 #if !defined(WINCE)
01011       /* Flush GDI buffer to ensure we don't conflict with the drawing thread. */
01012       GdiFlush();
01013 #endif
01014 
01015       /* The game loop is the part that can run asynchronously.
01016        * The rest except sleeping can't. */
01017       if (_draw_threaded) _draw_mutex->EndCritical();
01018       GameLoop();
01019       if (_draw_threaded) _draw_mutex->BeginCritical();
01020 
01021       if (_force_full_redraw) MarkWholeScreenDirty();
01022 
01023       _screen.dst_ptr = _wnd.buffer_bits;
01024       UpdateWindows();
01025       CheckPaletteAnim();
01026     } else {
01027 #if !defined(WINCE)
01028       /* Flush GDI buffer to ensure we don't conflict with the drawing thread. */
01029       GdiFlush();
01030 #endif
01031 
01032       /* Release the thread while sleeping */
01033       if (_draw_threaded) _draw_mutex->EndCritical();
01034       Sleep(1);
01035       if (_draw_threaded) _draw_mutex->BeginCritical();
01036 
01037       _screen.dst_ptr = _wnd.buffer_bits;
01038       NetworkDrawChatMessage();
01039       DrawMouseCursor();
01040     }
01041   }
01042 
01043   if (_draw_threaded) {
01044     _draw_continue = false;
01045     /* Sending signal if there is no thread blocked
01046      * is very valid and results in noop */
01047     _draw_mutex->SendSignal();
01048     _draw_mutex->EndCritical();
01049     _draw_thread->Join();
01050 
01051     delete _draw_mutex;
01052     delete _draw_thread;
01053   }
01054 }
01055 
01056 bool VideoDriver_Win32::ChangeResolution(int w, int h)
01057 {
01058   _wnd.width = _wnd.width_org = w;
01059   _wnd.height = _wnd.height_org = h;
01060 
01061   return this->MakeWindow(_fullscreen); // _wnd.fullscreen screws up ingame resolution switching
01062 }
01063 
01064 bool VideoDriver_Win32::ToggleFullscreen(bool full_screen)
01065 {
01066   return this->MakeWindow(full_screen);
01067 }
01068 
01069 bool VideoDriver_Win32::AfterBlitterChange()
01070 {
01071   return AllocateDibSection(_screen.width, _screen.height, true) && this->MakeWindow(_fullscreen);
01072 }