win32_v.cpp

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