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