OpenTTD Source 15.0-beta2
win32_v.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
7
10#include "../stdafx.h"
11#include "../openttd.h"
12#include "../error_func.h"
13#include "../gfx_func.h"
14#include "../os/windows/win32.h"
15#include "../blitter/factory.hpp"
16#include "../core/geometry_func.hpp"
17#include "../core/math_func.hpp"
18#include "../core/random_func.hpp"
19#include "../texteff.hpp"
20#include "../thread.h"
21#include "../progress.h"
22#include "../window_gui.h"
23#include "../window_func.h"
24#include "../framerate_type.h"
25#include "../library_loader.h"
26#include "../core/utf8.hpp"
27#include "win32_v.h"
28#include <windows.h>
29#include <imm.h>
30#include <versionhelpers.h>
31#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
32#include <winrt/Windows.UI.ViewManagement.h>
33#endif
34
35#include "../safeguards.h"
36
37/* Missing define in MinGW headers. */
38#ifndef MAPVK_VK_TO_CHAR
39#define MAPVK_VK_TO_CHAR (2)
40#endif
41
42#ifndef PM_QS_INPUT
43#define PM_QS_INPUT 0x20000
44#endif
45
46#ifndef WM_DPICHANGED
47#define WM_DPICHANGED 0x02E0
48#endif
49
50bool _window_maximize;
51static Dimension _bck_resolution;
52DWORD _imm_props;
53
55
56bool VideoDriver_Win32Base::ClaimMousePointer()
57{
58 MyShowCursor(false, true);
59 return true;
60}
61
63 uint8_t vk_from;
64 uint8_t vk_count;
65 uint8_t map_to;
66};
67
68#define AS(x, z) {x, 1, z}
69#define AM(x, y, z, w) {x, y - x + 1, z}
70
71static const Win32VkMapping _vk_mapping[] = {
72 /* Pageup stuff + up/down */
73 AM(VK_PRIOR, VK_DOWN, WKC_PAGEUP, WKC_DOWN),
74 /* Map letters & digits */
75 AM('A', 'Z', 'A', 'Z'),
76 AM('0', '9', '0', '9'),
77
78 AS(VK_ESCAPE, WKC_ESC),
79 AS(VK_PAUSE, WKC_PAUSE),
80 AS(VK_BACK, WKC_BACKSPACE),
81 AM(VK_INSERT, VK_DELETE, WKC_INSERT, WKC_DELETE),
82
83 AS(VK_SPACE, WKC_SPACE),
84 AS(VK_RETURN, WKC_RETURN),
85 AS(VK_TAB, WKC_TAB),
86
87 /* Function keys */
88 AM(VK_F1, VK_F12, WKC_F1, WKC_F12),
89
90 /* Numeric part */
91 AM(VK_NUMPAD0, VK_NUMPAD9, '0', '9'),
92 AS(VK_DIVIDE, WKC_NUM_DIV),
93 AS(VK_MULTIPLY, WKC_NUM_MUL),
94 AS(VK_SUBTRACT, WKC_NUM_MINUS),
95 AS(VK_ADD, WKC_NUM_PLUS),
96 AS(VK_DECIMAL, WKC_NUM_DECIMAL),
97
98 /* Other non-letter keys */
99 AS(0xBF, WKC_SLASH),
100 AS(0xBA, WKC_SEMICOLON),
101 AS(0xBB, WKC_EQUALS),
102 AS(0xDB, WKC_L_BRACKET),
103 AS(0xDC, WKC_BACKSLASH),
104 AS(0xDD, WKC_R_BRACKET),
105
106 AS(0xDE, WKC_SINGLEQUOTE),
107 AS(0xBC, WKC_COMMA),
108 AS(0xBD, WKC_MINUS),
109 AS(0xBE, WKC_PERIOD)
110};
111
112static uint MapWindowsKey(uint sym)
113{
114 uint key = 0;
115
116 for (const auto &map : _vk_mapping) {
117 if (IsInsideBS(sym, map.vk_from, map.vk_count)) {
118 key = sym - map.vk_from + map.map_to;
119 break;
120 }
121 }
122
123 if (GetAsyncKeyState(VK_SHIFT) < 0) key |= WKC_SHIFT;
124 if (GetAsyncKeyState(VK_CONTROL) < 0) key |= WKC_CTRL;
125 if (GetAsyncKeyState(VK_MENU) < 0) key |= WKC_ALT;
126 return key;
127}
128
131{
132 /* Check modes for the relevant fullscreen bpp */
133 return _support8bpp != S8BPP_HARDWARE ? 32 : BlitterFactory::GetCurrentBlitter()->GetScreenDepth();
134}
135
142bool VideoDriver_Win32Base::MakeWindow(bool full_screen, bool resize)
143{
144 /* full_screen is whether the new window should be fullscreen,
145 * _wnd.fullscreen is whether the current window is. */
146 _fullscreen = full_screen;
147
148 /* recreate window? */
149 if ((full_screen != this->fullscreen) && this->main_wnd) {
150 DestroyWindow(this->main_wnd);
151 this->main_wnd = 0;
152 }
153
154 if (full_screen) {
155 DEVMODE settings;
156
157 memset(&settings, 0, sizeof(settings));
158 settings.dmSize = sizeof(settings);
159 settings.dmFields =
160 DM_BITSPERPEL |
161 DM_PELSWIDTH |
162 DM_PELSHEIGHT;
163 settings.dmBitsPerPel = this->GetFullscreenBpp();
164 settings.dmPelsWidth = this->width_org;
165 settings.dmPelsHeight = this->height_org;
166
167 /* Check for 8 bpp support. */
168 if (settings.dmBitsPerPel == 8 && ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
169 settings.dmBitsPerPel = 32;
170 }
171
172 /* Test fullscreen with current resolution, if it fails use desktop resolution. */
173 if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
174 RECT r;
175 GetWindowRect(GetDesktopWindow(), &r);
176 /* Guard against recursion. If we already failed here once, just fall through to
177 * the next ChangeDisplaySettings call which will fail and error out appropriately. */
178 if ((int)settings.dmPelsWidth != r.right - r.left || (int)settings.dmPelsHeight != r.bottom - r.top) {
179 return this->ChangeResolution(r.right - r.left, r.bottom - r.top);
180 }
181 }
182
183 if (ChangeDisplaySettings(&settings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
184 this->MakeWindow(false, resize); // don't care about the result
185 return false; // the request failed
186 }
187 } else if (this->fullscreen) {
188 /* restore display? */
189 ChangeDisplaySettings(nullptr, 0);
190 /* restore the resolution */
191 this->width = _bck_resolution.width;
192 this->height = _bck_resolution.height;
193 }
194
195 {
196 RECT r;
197 DWORD style, showstyle;
198 int w, h;
199
200 showstyle = SW_SHOWNORMAL;
201 this->fullscreen = full_screen;
202 if (this->fullscreen) {
203 style = WS_POPUP;
204 SetRect(&r, 0, 0, this->width_org, this->height_org);
205 } else {
206 style = WS_OVERLAPPEDWINDOW;
207 /* On window creation, check if we were in maximize mode before */
208 if (_window_maximize) showstyle = SW_SHOWMAXIMIZED;
209 SetRect(&r, 0, 0, this->width, this->height);
210 }
211
212 AdjustWindowRect(&r, style, FALSE);
213 w = r.right - r.left;
214 h = r.bottom - r.top;
215
216 if (this->main_wnd != nullptr) {
217 if (!_window_maximize && resize) SetWindowPos(this->main_wnd, 0, 0, 0, w, h, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOMOVE);
218 } else {
219 int x = 0;
220 int y = 0;
221
222 /* For windowed mode, center on the workspace of the primary display. */
223 if (!this->fullscreen) {
224 MONITORINFO mi;
225 mi.cbSize = sizeof(mi);
226 GetMonitorInfo(MonitorFromWindow(0, MONITOR_DEFAULTTOPRIMARY), &mi);
227
228 x = (mi.rcWork.right - mi.rcWork.left - w) / 2;
229 y = (mi.rcWork.bottom - mi.rcWork.top - h) / 2;
230 }
231
232 std::string caption = VideoDriver::GetCaption();
233 this->main_wnd = CreateWindow(L"OTTD", OTTD2FS(caption).c_str(), style, x, y, w, h, 0, 0, GetModuleHandle(nullptr), this);
234 if (this->main_wnd == nullptr) UserError("CreateWindow failed");
235 ShowWindow(this->main_wnd, showstyle);
236 }
237 }
238
240
242 return true;
243}
244
246static LRESULT HandleCharMsg(uint keycode, char32_t charcode)
247{
248 static char32_t prev_char = 0;
249
250 /* Did we get a lead surrogate? If yes, store and exit. */
251 if (Utf16IsLeadSurrogate(charcode)) {
252 if (prev_char != 0) Debug(driver, 1, "Got two UTF-16 lead surrogates, dropping the first one");
253 prev_char = charcode;
254 return 0;
255 }
256
257 /* Stored lead surrogate and incoming trail surrogate? Combine and forward to input handling. */
258 if (prev_char != 0) {
259 if (Utf16IsTrailSurrogate(charcode)) {
260 charcode = Utf16DecodeSurrogate(prev_char, charcode);
261 } else {
262 Debug(driver, 1, "Got an UTF-16 lead surrogate without a trail surrogate, dropping the lead surrogate");
263 }
264 }
265 prev_char = 0;
266
267 HandleKeypress(keycode, charcode);
268
269 return 0;
270}
271
274{
275 return (_imm_props & IME_PROP_AT_CARET) && !(_imm_props & IME_PROP_SPECIAL_UI);
276}
277
279static void SetCompositionPos(HWND hwnd)
280{
281 HIMC hIMC = ImmGetContext(hwnd);
282 if (hIMC != nullptr) {
283 COMPOSITIONFORM cf;
284 cf.dwStyle = CFS_POINT;
285
286 if (EditBoxInGlobalFocus()) {
287 /* Get caret position. */
288 Point pt = _focused_window->GetCaretPosition();
289 cf.ptCurrentPos.x = _focused_window->left + pt.x;
290 cf.ptCurrentPos.y = _focused_window->top + pt.y;
291 } else {
292 cf.ptCurrentPos.x = 0;
293 cf.ptCurrentPos.y = 0;
294 }
295 ImmSetCompositionWindow(hIMC, &cf);
296 }
297 ImmReleaseContext(hwnd, hIMC);
298}
299
301static void SetCandidatePos(HWND hwnd)
302{
303 HIMC hIMC = ImmGetContext(hwnd);
304 if (hIMC != nullptr) {
305 CANDIDATEFORM cf;
306 cf.dwIndex = 0;
307 cf.dwStyle = CFS_EXCLUDE;
308
309 if (EditBoxInGlobalFocus()) {
310 Point pt = _focused_window->GetCaretPosition();
311 cf.ptCurrentPos.x = _focused_window->left + pt.x;
312 cf.ptCurrentPos.y = _focused_window->top + pt.y;
313 if (_focused_window->window_class == WC_CONSOLE) {
314 cf.rcArea.left = _focused_window->left;
315 cf.rcArea.top = _focused_window->top;
316 cf.rcArea.right = _focused_window->left + _focused_window->width;
317 cf.rcArea.bottom = _focused_window->top + _focused_window->height;
318 } else {
319 cf.rcArea.left = _focused_window->left + _focused_window->nested_focus->pos_x;
320 cf.rcArea.top = _focused_window->top + _focused_window->nested_focus->pos_y;
321 cf.rcArea.right = cf.rcArea.left + _focused_window->nested_focus->current_x;
322 cf.rcArea.bottom = cf.rcArea.top + _focused_window->nested_focus->current_y;
323 }
324 } else {
325 cf.ptCurrentPos.x = 0;
326 cf.ptCurrentPos.y = 0;
327 SetRectEmpty(&cf.rcArea);
328 }
329 ImmSetCandidateWindow(hIMC, &cf);
330 }
331 ImmReleaseContext(hwnd, hIMC);
332}
333
335static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
336{
337 HIMC hIMC = ImmGetContext(hwnd);
338
339 if (hIMC != nullptr) {
340 if (lParam & GCS_RESULTSTR) {
341 /* Read result string from the IME. */
342 LONG len = ImmGetCompositionString(hIMC, GCS_RESULTSTR, nullptr, 0); // Length is always in bytes, even in UNICODE build.
343 std::wstring str(len + 1, L'\0');
344 len = ImmGetCompositionString(hIMC, GCS_RESULTSTR, str.data(), len);
345 str[len / sizeof(wchar_t)] = L'\0';
346
347 /* Transmit text to windowing system. */
348 if (len > 0) {
349 HandleTextInput(nullptr, true); // Clear marked string.
350 HandleTextInput(FS2OTTD(str).c_str());
351 }
352 SetCompositionPos(hwnd);
353
354 /* Don't pass the result string on to the default window proc. */
355 lParam &= ~(GCS_RESULTSTR | GCS_RESULTCLAUSE | GCS_RESULTREADCLAUSE | GCS_RESULTREADSTR);
356 }
357
358 if ((lParam & GCS_COMPSTR) && DrawIMECompositionString()) {
359 /* Read composition string from the IME. */
360 LONG len = ImmGetCompositionString(hIMC, GCS_COMPSTR, nullptr, 0); // Length is always in bytes, even in UNICODE build.
361 std::wstring str(len + 1, L'\0');
362 len = ImmGetCompositionString(hIMC, GCS_COMPSTR, str.data(), len);
363 str[len / sizeof(wchar_t)] = L'\0';
364
365 if (len > 0) {
366 static char utf8_buf[1024];
367 convert_from_fs(str.c_str(), utf8_buf);
368
369 /* Convert caret position from bytes in the input string to a position in the UTF-8 encoded string. */
370 LONG caret_bytes = ImmGetCompositionString(hIMC, GCS_CURSORPOS, nullptr, 0);
371 Utf8View view(utf8_buf);
372 auto caret = view.begin();
373 const auto end = view.end();
374 for (const wchar_t *c = str.c_str(); *c != '\0' && caret != end && caret_bytes > 0; c++, caret_bytes--) {
375 /* Skip DBCS lead bytes or leading surrogates. */
376 if (Utf16IsLeadSurrogate(*c)) {
377 c++;
378 caret_bytes--;
379 }
380 ++caret;
381 }
382
383 HandleTextInput(utf8_buf, true, utf8_buf + caret.GetByteOffset());
384 } else {
385 HandleTextInput(nullptr, true);
386 }
387
388 lParam &= ~(GCS_COMPSTR | GCS_COMPATTR | GCS_COMPCLAUSE | GCS_CURSORPOS | GCS_DELTASTART);
389 }
390 }
391 ImmReleaseContext(hwnd, hIMC);
392
393 return lParam != 0 ? DefWindowProc(hwnd, WM_IME_COMPOSITION, wParam, lParam) : 0;
394}
395
397static void CancelIMEComposition(HWND hwnd)
398{
399 HIMC hIMC = ImmGetContext(hwnd);
400 if (hIMC != nullptr) ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
401 ImmReleaseContext(hwnd, hIMC);
402 /* Clear any marked string from the current edit box. */
403 HandleTextInput(nullptr, true);
404}
405
406static bool IsDarkModeEnabled()
407{
408 /* Only build if SDK is Windows 10 1803 or later. */
409#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
410 if (IsWindows10OrGreater()) {
411 try {
412 /*
413 * The official documented way to find out if the system is running in dark mode is to
414 * check the brightness of the current theme's colour.
415 * See: https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/ui/apply-windows-themes#know-when-dark-mode-is-enabled
416 *
417 * There are other variants floating around on the Internet, but they all rely on internal,
418 * undocumented Windows functions that may or may not work in the future.
419 */
420 winrt::Windows::UI::ViewManagement::UISettings settings;
421 auto foreground = settings.GetColorValue(winrt::Windows::UI::ViewManagement::UIColorType::Foreground);
422
423 /* If the Foreground colour is a light colour, the system is running in dark mode. */
424 return ((5 * foreground.G) + (2 * foreground.R) + foreground.B) > (8 * 128);
425 } catch (...) {
426 /* Some kind of error, like a too old Windows version. Just return false. */
427 return false;
428 }
429 }
430#endif /* defined(_MSC_VER) && defined(NTDDI_WIN10_RS4) */
431
432 return false;
433}
434
435static void SetDarkModeForWindow(HWND hWnd, bool dark_mode)
436{
437 /* Only build if SDK is Windows 10+. */
438#if defined(NTDDI_WIN10)
439 if (!IsWindows10OrGreater()) return;
440
441 /* This function is documented, but not supported on all Windows 10/11 SDK builds. For this
442 * reason, the code uses dynamic loading and ignores any errors for a best-effort result. */
443 static LibraryLoader _dwmapi("dwmapi.dll");
444 typedef HRESULT(WINAPI *PFNDWMSETWINDOWATTRIBUTE)(HWND, DWORD, LPCVOID, DWORD);
445 static PFNDWMSETWINDOWATTRIBUTE DwmSetWindowAttribute = _dwmapi.GetFunction("DwmSetWindowAttribute");
446
447 if (DwmSetWindowAttribute != nullptr) {
448 /* Contrary to the published documentation, DWMWA_USE_IMMERSIVE_DARK_MODE does not change the
449 * window chrome according to the current theme, but forces it to either light or dark mode.
450 * As such, the set value has to depend on the current theming mode.*/
451 BOOL value = dark_mode ? TRUE : FALSE;
452 if (DwmSetWindowAttribute(hWnd, 20 /* DWMWA_USE_IMMERSIVE_DARK_MODE */, &value, sizeof(value)) != S_OK) {
453 DwmSetWindowAttribute(hWnd, 19 /* DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 */, &value, sizeof(value)); // Ignore errors. It works or it doesn't.
454 }
455 }
456#endif /* defined(NTDDI_WIN10) */
457}
458
459LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
460{
461 static uint32_t keycode = 0;
462 static bool console = false;
463
464 const float SCROLL_BUILTIN_MULTIPLIER = 14.0f / WHEEL_DELTA;
465
466 VideoDriver_Win32Base *video_driver = (VideoDriver_Win32Base *)GetWindowLongPtr(hwnd, GWLP_USERDATA);
467
468 switch (msg) {
469 case WM_CREATE:
470 SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)((LPCREATESTRUCT)lParam)->lpCreateParams);
471 _cursor.in_window = false; // Win32 has mouse tracking.
472 SetCompositionPos(hwnd);
473 _imm_props = ImmGetProperty(GetKeyboardLayout(0), IGP_PROPERTY);
474
475 /* Enable dark mode theming for window chrome. */
476 SetDarkModeForWindow(hwnd, IsDarkModeEnabled());
477 break;
478
479 case WM_SETTINGCHANGE:
480 /* Synchronize dark mode theming state. */
481 SetDarkModeForWindow(hwnd, IsDarkModeEnabled());
482 break;
483
484 case WM_PAINT: {
485 RECT r;
486 GetUpdateRect(hwnd, &r, FALSE);
487 video_driver->MakeDirty(r.left, r.top, r.right - r.left, r.bottom - r.top);
488
489 ValidateRect(hwnd, nullptr);
490 return 0;
491 }
492
493 case WM_PALETTECHANGED:
494 if ((HWND)wParam == hwnd) return 0;
495 [[fallthrough]];
496
497 case WM_QUERYNEWPALETTE:
498 video_driver->PaletteChanged(hwnd);
499 return 0;
500
501 case WM_CLOSE:
502 HandleExitGameRequest();
503 return 0;
504
505 case WM_DESTROY:
506 if (_window_maximize) _cur_resolution = _bck_resolution;
507 return 0;
508
509 case WM_LBUTTONDOWN:
510 SetCapture(hwnd);
511 _left_button_down = true;
513 return 0;
514
515 case WM_LBUTTONUP:
516 ReleaseCapture();
517 _left_button_down = false;
518 _left_button_clicked = false;
520 return 0;
521
522 case WM_RBUTTONDOWN:
523 SetCapture(hwnd);
524 _right_button_down = true;
527 return 0;
528
529 case WM_RBUTTONUP:
530 ReleaseCapture();
531 _right_button_down = false;
533 return 0;
534
535 case WM_MOUSELEAVE:
536 UndrawMouseCursor();
537 _cursor.in_window = false;
538
539 if (!_left_button_down && !_right_button_down) MyShowCursor(true);
540 return 0;
541
542 case WM_MOUSEMOVE: {
543 int x = (int16_t)LOWORD(lParam);
544 int y = (int16_t)HIWORD(lParam);
545
546 /* If the mouse was not in the window and it has moved it means it has
547 * come into the window, so start drawing the mouse. Also start
548 * tracking the mouse for exiting the window */
549 if (!_cursor.in_window) {
550 _cursor.in_window = true;
551 TRACKMOUSEEVENT tme;
552 tme.cbSize = sizeof(tme);
553 tme.dwFlags = TME_LEAVE;
554 tme.hwndTrack = hwnd;
555
556 TrackMouseEvent(&tme);
557 }
558
559 if (_cursor.fix_at) {
560 /* Get all queued mouse events now in case we have to warp the cursor. In the
561 * end, we only care about the current mouse position and not bygone events. */
562 MSG m;
563 while (PeekMessage(&m, hwnd, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE | PM_NOYIELD | PM_QS_INPUT)) {
564 x = (int16_t)LOWORD(m.lParam);
565 y = (int16_t)HIWORD(m.lParam);
566 }
567 }
568
569 if (_cursor.UpdateCursorPosition(x, y)) {
570 POINT pt;
571 pt.x = _cursor.pos.x;
572 pt.y = _cursor.pos.y;
573 ClientToScreen(hwnd, &pt);
574 SetCursorPos(pt.x, pt.y);
575 }
576 MyShowCursor(false);
578 return 0;
579 }
580
581 case WM_INPUTLANGCHANGE:
582 _imm_props = ImmGetProperty(GetKeyboardLayout(0), IGP_PROPERTY);
583 break;
584
585 case WM_IME_SETCONTEXT:
586 /* Don't show the composition window if we draw the string ourself. */
587 if (DrawIMECompositionString()) lParam &= ~ISC_SHOWUICOMPOSITIONWINDOW;
588 break;
589
590 case WM_IME_STARTCOMPOSITION:
591 SetCompositionPos(hwnd);
592 if (DrawIMECompositionString()) return 0;
593 break;
594
595 case WM_IME_COMPOSITION:
596 return HandleIMEComposition(hwnd, wParam, lParam);
597
598 case WM_IME_ENDCOMPOSITION:
599 /* Clear any pending composition string. */
600 HandleTextInput(nullptr, true);
601 if (DrawIMECompositionString()) return 0;
602 break;
603
604 case WM_IME_NOTIFY:
605 if (wParam == IMN_OPENCANDIDATE) SetCandidatePos(hwnd);
606 break;
607
608 case WM_DEADCHAR:
609 console = GB(lParam, 16, 8) == 41;
610 return 0;
611
612 case WM_CHAR: {
613 uint scancode = GB(lParam, 16, 8);
614 uint charcode = wParam;
615
616 /* If the console key is a dead-key, we need to press it twice to get a WM_CHAR message.
617 * But we then get two WM_CHAR messages, so ignore the first one */
618 if (console && scancode == 41) {
619 console = false;
620 return 0;
621 }
622
623 /* IMEs and other input methods sometimes send a WM_CHAR without a WM_KEYDOWN,
624 * clear the keycode so a previous WM_KEYDOWN doesn't become 'stuck'. */
625 uint cur_keycode = keycode;
626 keycode = 0;
627
628 return HandleCharMsg(cur_keycode, charcode);
629 }
630
631 case WM_KEYDOWN: {
632 /* No matter the keyboard layout, we will map the '~' to the console. */
633 uint scancode = GB(lParam, 16, 8);
634 keycode = scancode == 41 ? (uint)WKC_BACKQUOTE : MapWindowsKey(wParam);
635
636 uint charcode = MapVirtualKey(wParam, MAPVK_VK_TO_CHAR);
637
638 /* No character translation? */
639 if (charcode == 0) {
640 HandleKeypress(keycode, 0);
641 return 0;
642 }
643
644 /* If an edit box is in focus, wait for the corresponding WM_CHAR message. */
645 if (!EditBoxInGlobalFocus()) {
646 /* Is the console key a dead key? If yes, ignore the first key down event. */
647 if (HasBit(charcode, 31) && !console) {
648 if (scancode == 41) {
649 console = true;
650 return 0;
651 }
652 }
653 console = false;
654
655 /* IMEs and other input methods sometimes send a WM_CHAR without a WM_KEYDOWN,
656 * clear the keycode so a previous WM_KEYDOWN doesn't become 'stuck'. */
657 uint cur_keycode = keycode;
658 keycode = 0;
659
660 return HandleCharMsg(cur_keycode, LOWORD(charcode));
661 }
662
663 return 0;
664 }
665
666 case WM_SYSKEYDOWN: // user presses F10 or Alt, both activating the title-menu
667 switch (wParam) {
668 case VK_RETURN:
669 case 'F': // Full Screen on ALT + ENTER/F
670 ToggleFullScreen(!video_driver->fullscreen);
671 return 0;
672
673 case VK_MENU: // Just ALT
674 return 0; // do nothing
675
676 case VK_F10: // F10, ignore activation of menu
677 HandleKeypress(MapWindowsKey(wParam), 0);
678 return 0;
679
680 default: // ALT in combination with something else
681 HandleKeypress(MapWindowsKey(wParam), 0);
682 break;
683 }
684 break;
685
686 case WM_SIZE:
687 if (wParam != SIZE_MINIMIZED) {
688 /* Set maximized flag when we maximize (obviously), but also when we
689 * switched to fullscreen from a maximized state */
690 _window_maximize = (wParam == SIZE_MAXIMIZED || (_window_maximize && _fullscreen));
691 if (_window_maximize || _fullscreen) _bck_resolution = _cur_resolution;
692 video_driver->ClientSizeChanged(LOWORD(lParam), HIWORD(lParam));
693 }
694 return 0;
695
696 case WM_SIZING: {
697 RECT *r = (RECT*)lParam;
698 RECT r2;
699 int w, h;
700
701 SetRect(&r2, 0, 0, 0, 0);
702 AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
703
704 w = r->right - r->left - (r2.right - r2.left);
705 h = r->bottom - r->top - (r2.bottom - r2.top);
706 w = std::max(w, 64);
707 h = std::max(h, 64);
708 SetRect(&r2, 0, 0, w, h);
709
710 AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
711 w = r2.right - r2.left;
712 h = r2.bottom - r2.top;
713
714 switch (wParam) {
715 case WMSZ_BOTTOM:
716 r->bottom = r->top + h;
717 break;
718
719 case WMSZ_BOTTOMLEFT:
720 r->bottom = r->top + h;
721 r->left = r->right - w;
722 break;
723
724 case WMSZ_BOTTOMRIGHT:
725 r->bottom = r->top + h;
726 r->right = r->left + w;
727 break;
728
729 case WMSZ_LEFT:
730 r->left = r->right - w;
731 break;
732
733 case WMSZ_RIGHT:
734 r->right = r->left + w;
735 break;
736
737 case WMSZ_TOP:
738 r->top = r->bottom - h;
739 break;
740
741 case WMSZ_TOPLEFT:
742 r->top = r->bottom - h;
743 r->left = r->right - w;
744 break;
745
746 case WMSZ_TOPRIGHT:
747 r->top = r->bottom - h;
748 r->right = r->left + w;
749 break;
750 }
751 return TRUE;
752 }
753
754 case WM_DPICHANGED: {
755 auto did_adjust = AdjustGUIZoom(true);
756
757 /* Resize the window to match the new DPI setting. */
758 RECT *prcNewWindow = (RECT *)lParam;
759 SetWindowPos(hwnd,
760 nullptr,
761 prcNewWindow->left,
762 prcNewWindow->top,
763 prcNewWindow->right - prcNewWindow->left,
764 prcNewWindow->bottom - prcNewWindow->top,
765 SWP_NOZORDER | SWP_NOACTIVATE);
766
767 if (did_adjust) ReInitAllWindows(true);
768
769 return 0;
770 }
771
772/* needed for wheel */
773#if !defined(WM_MOUSEWHEEL)
774# define WM_MOUSEWHEEL 0x020A
775#endif /* WM_MOUSEWHEEL */
776#if !defined(WM_MOUSEHWHEEL)
777# define WM_MOUSEHWHEEL 0x020E
778#endif /* WM_MOUSEHWHEEL */
779#if !defined(GET_WHEEL_DELTA_WPARAM)
780# define GET_WHEEL_DELTA_WPARAM(wparam) ((short)HIWORD(wparam))
781#endif /* GET_WHEEL_DELTA_WPARAM */
782
783 case WM_MOUSEWHEEL: {
784 int delta = GET_WHEEL_DELTA_WPARAM(wParam);
785
786 if (delta < 0) {
787 _cursor.wheel++;
788 } else if (delta > 0) {
789 _cursor.wheel--;
790 }
791
792 _cursor.v_wheel -= static_cast<float>(delta) * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier;
793 _cursor.wheel_moved = true;
795 return 0;
796 }
797
798 case WM_MOUSEHWHEEL: {
799 int delta = GET_WHEEL_DELTA_WPARAM(wParam);
800
801 _cursor.h_wheel += static_cast<float>(delta) * SCROLL_BUILTIN_MULTIPLIER * _settings_client.gui.scrollwheel_multiplier;
802 _cursor.wheel_moved = true;
804 return 0;
805 }
806
807 case WM_SETFOCUS:
808 video_driver->has_focus = true;
809 SetCompositionPos(hwnd);
810 break;
811
812 case WM_KILLFOCUS:
813 video_driver->has_focus = false;
814 break;
815
816 case WM_ACTIVATE: {
817 /* Don't do anything if we are closing openttd */
818 if (_exit_game) break;
819
820 bool active = (LOWORD(wParam) != WA_INACTIVE);
821 bool minimized = (HIWORD(wParam) != 0);
822 if (video_driver->fullscreen) {
823 if (active && minimized) {
824 /* Restore the game window */
825 Dimension d = _bck_resolution; // Save current non-fullscreen window size as it will be overwritten by ShowWindow.
826 ShowWindow(hwnd, SW_RESTORE);
827 _bck_resolution = d;
828 video_driver->MakeWindow(true);
829 } else if (!active && !minimized) {
830 /* Minimise the window and restore desktop */
831 ShowWindow(hwnd, SW_MINIMIZE);
832 ChangeDisplaySettings(nullptr, 0);
833 }
834 }
835 break;
836 }
837 }
838
839 return DefWindowProc(hwnd, msg, wParam, lParam);
840}
841
842static void RegisterWndClass()
843{
844 static bool registered = false;
845
846 if (registered) return;
847
848 HINSTANCE hinst = GetModuleHandle(nullptr);
849 WNDCLASS wnd = {
850 CS_OWNDC,
851 WndProcGdi,
852 0,
853 0,
854 hinst,
855 LoadIcon(hinst, MAKEINTRESOURCE(100)),
856 LoadCursor(nullptr, IDC_ARROW),
857 0,
858 0,
859 L"OTTD"
860 };
861
862 registered = true;
863 if (!RegisterClass(&wnd)) UserError("RegisterClass failed");
864}
865
866static const Dimension default_resolutions[] = {
867 { 640, 480 },
868 { 800, 600 },
869 { 1024, 768 },
870 { 1152, 864 },
871 { 1280, 800 },
872 { 1280, 960 },
873 { 1280, 1024 },
874 { 1400, 1050 },
875 { 1600, 1200 },
876 { 1680, 1050 },
877 { 1920, 1200 }
878};
879
880static void FindResolutions(uint8_t bpp)
881{
882 _resolutions.clear();
883
884 DEVMODE dm;
885 for (uint i = 0; EnumDisplaySettings(nullptr, i, &dm) != 0; i++) {
886 if (dm.dmBitsPerPel != bpp || dm.dmPelsWidth < 640 || dm.dmPelsHeight < 480) continue;
887 if (std::ranges::find(_resolutions, Dimension(dm.dmPelsWidth, dm.dmPelsHeight)) != _resolutions.end()) continue;
888 _resolutions.emplace_back(dm.dmPelsWidth, dm.dmPelsHeight);
889 }
890
891 /* We have found no resolutions, show the default list */
892 if (_resolutions.empty()) {
893 _resolutions.assign(std::begin(default_resolutions), std::end(default_resolutions));
894 }
895
896 SortResolutions();
897}
898
899void VideoDriver_Win32Base::Initialize()
900{
901 this->UpdateAutoResolution();
902
903 RegisterWndClass();
904 FindResolutions(this->GetFullscreenBpp());
905
906 /* fullscreen uses those */
907 this->width = this->width_org = _cur_resolution.width;
908 this->height = this->height_org = _cur_resolution.height;
909
910 Debug(driver, 2, "Resolution for display: {}x{}", _cur_resolution.width, _cur_resolution.height);
911}
912
914{
915 DestroyWindow(this->main_wnd);
916
917 if (this->fullscreen) ChangeDisplaySettings(nullptr, 0);
918 MyShowCursor(true);
919}
920void VideoDriver_Win32Base::MakeDirty(int left, int top, int width, int height)
921{
922 Rect r = {left, top, left + width, top + height};
923 this->dirty_rect = BoundingRect(this->dirty_rect, r);
924}
925
927{
928 if (!CopyPalette(_local_palette)) return;
929 this->MakeDirty(0, 0, _screen.width, _screen.height);
930}
931
933{
934 bool old_ctrl_pressed = _ctrl_pressed;
935
936 _ctrl_pressed = this->has_focus && GetAsyncKeyState(VK_CONTROL) < 0;
937 _shift_pressed = this->has_focus && GetAsyncKeyState(VK_SHIFT) < 0;
938
939 /* Speedup when pressing tab, except when using ALT+TAB
940 * to switch to another application. */
941 this->fast_forward_key_pressed = this->has_focus && GetAsyncKeyState(VK_TAB) < 0 && GetAsyncKeyState(VK_MENU) >= 0;
942
943 /* Determine which directional keys are down. */
944 if (this->has_focus) {
945 _dirkeys =
946 (GetAsyncKeyState(VK_LEFT) < 0 ? 1 : 0) +
947 (GetAsyncKeyState(VK_UP) < 0 ? 2 : 0) +
948 (GetAsyncKeyState(VK_RIGHT) < 0 ? 4 : 0) +
949 (GetAsyncKeyState(VK_DOWN) < 0 ? 8 : 0);
950 } else {
951 _dirkeys = 0;
952 }
953
954 if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
955}
956
958{
959 MSG mesg;
960
961 if (!PeekMessage(&mesg, nullptr, 0, 0, PM_REMOVE)) return false;
962
963 /* Convert key messages to char messages if we want text input. */
964 if (EditBoxInGlobalFocus()) TranslateMessage(&mesg);
965 DispatchMessage(&mesg);
966
967 return true;
968}
969
971{
972 this->StartGameThread();
973
974 for (;;) {
975 if (_exit_game) break;
976
977 this->Tick();
978 this->SleepTillNextTick();
979 }
980
981 this->StopGameThread();
982}
983
984void VideoDriver_Win32Base::ClientSizeChanged(int w, int h, bool force)
985{
986 /* Allocate backing store of the new size. */
987 if (this->AllocateBackingStore(w, h, force)) {
989
991
993 }
994}
995
997{
998 if (_window_maximize) ShowWindow(this->main_wnd, SW_SHOWNORMAL);
999
1000 this->width = this->width_org = w;
1001 this->height = this->height_org = h;
1002
1003 return this->MakeWindow(_fullscreen); // _wnd.fullscreen screws up ingame resolution switching
1004}
1005
1007{
1008 bool res = this->MakeWindow(full_screen);
1009
1011 return res;
1012}
1013
1020
1021static BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM data)
1022{
1023 auto &list = *reinterpret_cast<std::vector<int>*>(data);
1024
1025 MONITORINFOEX monitorInfo = {};
1026 monitorInfo.cbSize = sizeof(MONITORINFOEX);
1027 GetMonitorInfo(hMonitor, &monitorInfo);
1028
1029 DEVMODE devMode = {};
1030 devMode.dmSize = sizeof(DEVMODE);
1031 devMode.dmDriverExtra = 0;
1032 EnumDisplaySettings(monitorInfo.szDevice, ENUM_CURRENT_SETTINGS, &devMode);
1033
1034 if (devMode.dmDisplayFrequency != 0) list.push_back(devMode.dmDisplayFrequency);
1035 return true;
1036}
1037
1039{
1040 std::vector<int> rates = {};
1041 EnumDisplayMonitors(nullptr, nullptr, MonitorEnumProc, reinterpret_cast<LPARAM>(&rates));
1042 return rates;
1043}
1044
1046{
1047 return { static_cast<uint>(GetSystemMetrics(SM_CXSCREEN)), static_cast<uint>(GetSystemMetrics(SM_CYSCREEN)) };
1048}
1049
1051{
1052 typedef UINT (WINAPI *PFNGETDPIFORWINDOW)(HWND hwnd);
1053 typedef UINT (WINAPI *PFNGETDPIFORSYSTEM)(VOID);
1054 typedef HRESULT (WINAPI *PFNGETDPIFORMONITOR)(HMONITOR hMonitor, int dpiType, UINT *dpiX, UINT *dpiY);
1055
1056 static PFNGETDPIFORWINDOW _GetDpiForWindow = nullptr;
1057 static PFNGETDPIFORSYSTEM _GetDpiForSystem = nullptr;
1058 static PFNGETDPIFORMONITOR _GetDpiForMonitor = nullptr;
1059
1060 static bool init_done = false;
1061 if (!init_done) {
1062 init_done = true;
1063 static LibraryLoader _user32("user32.dll");
1064 static LibraryLoader _shcore("shcore.dll");
1065 _GetDpiForWindow = _user32.GetFunction("GetDpiForWindow");
1066 _GetDpiForSystem = _user32.GetFunction("GetDpiForSystem");
1067 _GetDpiForMonitor = _shcore.GetFunction("GetDpiForMonitor");
1068 }
1069
1070 UINT cur_dpi = 0;
1071
1072 if (cur_dpi == 0 && _GetDpiForWindow != nullptr && this->main_wnd != nullptr) {
1073 /* Per window DPI is supported since Windows 10 Ver 1607. */
1074 cur_dpi = _GetDpiForWindow(this->main_wnd);
1075 }
1076 if (cur_dpi == 0 && _GetDpiForMonitor != nullptr && this->main_wnd != nullptr) {
1077 /* Per monitor is supported since Windows 8.1. */
1078 UINT dpiX, dpiY;
1079 if (SUCCEEDED(_GetDpiForMonitor(MonitorFromWindow(this->main_wnd, MONITOR_DEFAULTTOPRIMARY), 0 /* MDT_EFFECTIVE_DPI */, &dpiX, &dpiY))) {
1080 cur_dpi = dpiX; // X and Y are always identical.
1081 }
1082 }
1083 if (cur_dpi == 0 && _GetDpiForSystem != nullptr) {
1084 /* Fall back to system DPI. */
1085 cur_dpi = _GetDpiForSystem();
1086 }
1087
1088 return cur_dpi > 0 ? cur_dpi / 96.0f : 1.0f; // Default Windows DPI value is 96.
1089}
1090
1092{
1093 if (this->buffer_locked) return false;
1094 this->buffer_locked = true;
1095
1096 _screen.dst_ptr = this->GetVideoPointer();
1097 assert(_screen.dst_ptr != nullptr);
1098
1099 return true;
1100}
1101
1103{
1104 assert(_screen.dst_ptr != nullptr);
1105 if (_screen.dst_ptr != nullptr) {
1106 /* Hand video buffer back to the drawing backend. */
1107 this->ReleaseVideoPointer();
1108 _screen.dst_ptr = nullptr;
1109 }
1110
1111 this->buffer_locked = false;
1112}
1113
1114
1115static FVideoDriver_Win32GDI iFVideoDriver_Win32GDI;
1116
1117std::optional<std::string_view> VideoDriver_Win32GDI::Start(const StringList &param)
1118{
1119 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
1120
1121 this->Initialize();
1122
1123 this->MakePalette();
1125 this->MakeWindow(_fullscreen);
1126
1128
1129 this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
1130
1131 return std::nullopt;
1132}
1133
1135{
1136 DeleteObject(this->gdi_palette);
1137 DeleteObject(this->dib_sect);
1138
1140}
1141
1143{
1145
1146 w = std::max(w, 64);
1147 h = std::max(h, 64);
1148
1149 if (!force && w == _screen.width && h == _screen.height) return false;
1150
1151 BITMAPINFO *bi = (BITMAPINFO *)new char[sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 256]();
1152 bi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
1153
1154 bi->bmiHeader.biWidth = this->width = w;
1155 bi->bmiHeader.biHeight = -(this->height = h);
1156
1157 bi->bmiHeader.biPlanes = 1;
1158 bi->bmiHeader.biBitCount = bpp;
1159 bi->bmiHeader.biCompression = BI_RGB;
1160
1161 if (this->dib_sect) DeleteObject(this->dib_sect);
1162
1163 HDC dc = GetDC(0);
1164 this->dib_sect = CreateDIBSection(dc, bi, DIB_RGB_COLORS, (VOID **)&this->buffer_bits, nullptr, 0);
1165 if (this->dib_sect == nullptr) {
1166 delete[] bi;
1167 UserError("CreateDIBSection failed");
1168 }
1169 ReleaseDC(0, dc);
1170
1171 _screen.width = w;
1172 _screen.pitch = (bpp == 8) ? Align(w, 4) : w;
1173 _screen.height = h;
1174 _screen.dst_ptr = this->GetVideoPointer();
1175
1176 delete[] bi;
1177 return true;
1178}
1179
1181{
1182 assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
1183 return this->AllocateBackingStore(_screen.width, _screen.height, true) && this->MakeWindow(_fullscreen, false);
1184}
1185
1186void VideoDriver_Win32GDI::MakePalette()
1187{
1189
1190 LOGPALETTE *pal = (LOGPALETTE *)new char[sizeof(LOGPALETTE) + (256 - 1) * sizeof(PALETTEENTRY)]();
1191
1192 pal->palVersion = 0x300;
1193 pal->palNumEntries = 256;
1194
1195 for (uint i = 0; i != 256; i++) {
1196 pal->palPalEntry[i].peRed = _local_palette.palette[i].r;
1197 pal->palPalEntry[i].peGreen = _local_palette.palette[i].g;
1198 pal->palPalEntry[i].peBlue = _local_palette.palette[i].b;
1199 pal->palPalEntry[i].peFlags = 0;
1200
1201 }
1202 this->gdi_palette = CreatePalette(pal);
1203 delete[] pal;
1204 if (this->gdi_palette == nullptr) UserError("CreatePalette failed!\n");
1205}
1206
1207void VideoDriver_Win32GDI::UpdatePalette(HDC dc, uint start, uint count)
1208{
1209 RGBQUAD rgb[256];
1210
1211 for (uint i = 0; i != count; i++) {
1212 rgb[i].rgbRed = _local_palette.palette[start + i].r;
1213 rgb[i].rgbGreen = _local_palette.palette[start + i].g;
1214 rgb[i].rgbBlue = _local_palette.palette[start + i].b;
1215 rgb[i].rgbReserved = 0;
1216 }
1217
1218 SetDIBColorTable(dc, start, count, rgb);
1219}
1220
1222{
1223 HDC hDC = GetWindowDC(hWnd);
1224 HPALETTE hOldPalette = SelectPalette(hDC, this->gdi_palette, FALSE);
1225 UINT nChanged = RealizePalette(hDC);
1226
1227 SelectPalette(hDC, hOldPalette, TRUE);
1228 ReleaseDC(hWnd, hDC);
1229 if (nChanged != 0) this->MakeDirty(0, 0, _screen.width, _screen.height);
1230}
1231
1233{
1234 PerformanceMeasurer framerate(PFE_VIDEO);
1235
1236 if (IsEmptyRect(this->dirty_rect)) return;
1237
1238 HDC dc = GetDC(this->main_wnd);
1239 HDC dc2 = CreateCompatibleDC(dc);
1240
1241 HBITMAP old_bmp = (HBITMAP)SelectObject(dc2, this->dib_sect);
1242 HPALETTE old_palette = SelectPalette(dc, this->gdi_palette, FALSE);
1243
1244 if (_local_palette.count_dirty != 0) {
1246
1247 switch (blitter->UsePaletteAnimation()) {
1249 this->UpdatePalette(dc2, _local_palette.first_dirty, _local_palette.count_dirty);
1250 break;
1251
1254 break;
1255 }
1256
1258 break;
1259
1260 default:
1261 NOT_REACHED();
1262 }
1264 }
1265
1266 BitBlt(dc, 0, 0, this->width, this->height, dc2, 0, 0, SRCCOPY);
1267 SelectPalette(dc, old_palette, TRUE);
1268 SelectObject(dc2, old_bmp);
1269 DeleteDC(dc2);
1270
1271 ReleaseDC(this->main_wnd, dc);
1272
1273 this->dirty_rect = {};
1274}
1275
1276#ifdef _DEBUG
1277/* Keep this function here..
1278 * It allows you to redraw the screen from within the MSVC debugger */
1279/* static */ int VideoDriver_Win32GDI::RedrawScreenDebug()
1280{
1281 static int _fooctr;
1282
1284
1285 _screen.dst_ptr = drv->GetVideoPointer();
1286 UpdateWindows();
1287
1288 drv->Paint();
1289 GdiFlush();
1290
1291 return _fooctr++;
1292}
1293#endif
1294
1295#ifdef WITH_OPENGL
1296
1297#include <GL/gl.h>
1298#include "../3rdparty/opengl/glext.h"
1299#include "../3rdparty/opengl/wglext.h"
1300#include "opengl.h"
1301
1302#ifndef PFD_SUPPORT_COMPOSITION
1303# define PFD_SUPPORT_COMPOSITION 0x00008000
1304#endif
1305
1306static PFNWGLCREATECONTEXTATTRIBSARBPROC _wglCreateContextAttribsARB = nullptr;
1307static PFNWGLSWAPINTERVALEXTPROC _wglSwapIntervalEXT = nullptr;
1308static bool _hasWGLARBCreateContextProfile = false;
1309
1311static OGLProc GetOGLProcAddressCallback(const char *proc)
1312{
1313 OGLProc ret = reinterpret_cast<OGLProc>(wglGetProcAddress(proc));
1314 if (ret == nullptr) {
1315 /* Non-extension GL function? Try normal loading. */
1316 ret = reinterpret_cast<OGLProc>(GetProcAddress(GetModuleHandle(L"opengl32"), proc));
1317 }
1318 return ret;
1319}
1320
1326static std::optional<std::string_view> SelectPixelFormat(HDC dc)
1327{
1328 PIXELFORMATDESCRIPTOR pfd = {
1329 sizeof(PIXELFORMATDESCRIPTOR), // Size of this struct.
1330 1, // Version of this struct.
1331 PFD_DRAW_TO_WINDOW | // Require window support.
1332 PFD_SUPPORT_OPENGL | // Require OpenGL support.
1333 PFD_DOUBLEBUFFER | // Use double buffering.
1334 PFD_DEPTH_DONTCARE,
1335 PFD_TYPE_RGBA, // Request RGBA format.
1336 24, // 24 bpp (excluding alpha).
1337 0, 0, 0, 0, 0, 0, 0, 0, // Colour bits and shift ignored.
1338 0, 0, 0, 0, 0, // No accumulation buffer.
1339 0, 0, // No depth/stencil buffer.
1340 0, // No aux buffers.
1341 PFD_MAIN_PLANE, // Main layer.
1342 0, 0, 0, 0 // Ignored/reserved.
1343 };
1344
1345 pfd.dwFlags |= PFD_SUPPORT_COMPOSITION; // Make OpenTTD compatible with Aero.
1346
1347 /* Choose a suitable pixel format. */
1348 int format = ChoosePixelFormat(dc, &pfd);
1349 if (format == 0) return "No suitable pixel format found";
1350 if (!SetPixelFormat(dc, format, &pfd)) return "Can't set pixel format";
1351
1352 return std::nullopt;
1353}
1354
1356static void LoadWGLExtensions()
1357{
1358 /* Querying the supported WGL extensions and loading the matching
1359 * functions requires a valid context, even for the extensions
1360 * regarding context creation. To get around this, we create
1361 * a dummy window with a dummy context. The extension functions
1362 * remain valid even after this context is destroyed. */
1363 HWND wnd = CreateWindow(L"STATIC", L"dummy", WS_OVERLAPPEDWINDOW, 0, 0, 0, 0, nullptr, nullptr, GetModuleHandle(nullptr), nullptr);
1364 HDC dc = GetDC(wnd);
1365
1366 /* Set pixel format of the window. */
1367 if (SelectPixelFormat(dc) == std::nullopt) {
1368 /* Create rendering context. */
1369 HGLRC rc = wglCreateContext(dc);
1370 if (rc != nullptr) {
1371 wglMakeCurrent(dc, rc);
1372
1373#ifdef __MINGW32__
1374 /* GCC doesn't understand the expected usage of wglGetProcAddress(). */
1375#pragma GCC diagnostic push
1376#pragma GCC diagnostic ignored "-Wcast-function-type"
1377#endif /* __MINGW32__ */
1378
1379 /* Get list of WGL extensions. */
1380 PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB");
1381 if (wglGetExtensionsStringARB != nullptr) {
1382 const char *wgl_exts = wglGetExtensionsStringARB(dc);
1383 /* Bind supported functions. */
1384 if (FindStringInExtensionList(wgl_exts, "WGL_ARB_create_context") != nullptr) {
1385 _wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");
1386 }
1387 _hasWGLARBCreateContextProfile = FindStringInExtensionList(wgl_exts, "WGL_ARB_create_context_profile") != nullptr;
1388 if (FindStringInExtensionList(wgl_exts, "WGL_EXT_swap_control") != nullptr) {
1389 _wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");
1390 }
1391 }
1392
1393#ifdef __MINGW32__
1394#pragma GCC diagnostic pop
1395#endif
1396 wglMakeCurrent(nullptr, nullptr);
1397 wglDeleteContext(rc);
1398 }
1399 }
1400
1401 ReleaseDC(wnd, dc);
1402 DestroyWindow(wnd);
1403}
1404
1405static FVideoDriver_Win32OpenGL iFVideoDriver_Win32OpenGL;
1406
1407std::optional<std::string_view> VideoDriver_Win32OpenGL::Start(const StringList &param)
1408{
1409 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
1410
1411 Dimension old_res = _cur_resolution; // Save current screen resolution in case of errors, as MakeWindow invalidates it.
1412
1413 LoadWGLExtensions();
1414
1415 this->Initialize();
1416 this->MakeWindow(_fullscreen);
1417
1418 /* Create and initialize OpenGL context. */
1419 auto err = this->AllocateContext();
1420 if (err) {
1421 this->Stop();
1422 _cur_resolution = old_res;
1423 return err;
1424 }
1425
1426 this->driver_info = GetName();
1427 this->driver_info += " (";
1428 this->driver_info += OpenGLBackend::Get()->GetDriverName();
1429 this->driver_info += ")";
1430
1431 this->ClientSizeChanged(this->width, this->height, true);
1432 /* We should have a valid screen buffer now. If not, something went wrong and we should abort. */
1433 if (_screen.dst_ptr == nullptr) {
1434 this->Stop();
1435 _cur_resolution = old_res;
1436 return "Can't get pointer to screen buffer";
1437 }
1438 /* Main loop expects to start with the buffer unmapped. */
1439 this->ReleaseVideoPointer();
1440
1442
1443 this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
1444
1445 return std::nullopt;
1446}
1447
1448void VideoDriver_Win32OpenGL::Stop()
1449{
1450 this->DestroyContext();
1452}
1453
1454void VideoDriver_Win32OpenGL::DestroyContext()
1455{
1457
1458 wglMakeCurrent(nullptr, nullptr);
1459 if (this->gl_rc != nullptr) {
1460 wglDeleteContext(this->gl_rc);
1461 this->gl_rc = nullptr;
1462 }
1463 if (this->dc != nullptr) {
1464 ReleaseDC(this->main_wnd, this->dc);
1465 this->dc = nullptr;
1466 }
1467}
1468
1469void VideoDriver_Win32OpenGL::ToggleVsync(bool vsync)
1470{
1471 if (_wglSwapIntervalEXT != nullptr) {
1472 _wglSwapIntervalEXT(vsync);
1473 } else if (vsync) {
1474 Debug(driver, 0, "OpenGL: Vsync requested, but not supported by driver");
1475 }
1476}
1477
1478std::optional<std::string_view> VideoDriver_Win32OpenGL::AllocateContext()
1479{
1480 this->dc = GetDC(this->main_wnd);
1481
1482 auto err = SelectPixelFormat(this->dc);
1483 if (err) return err;
1484
1485 HGLRC rc = nullptr;
1486
1487 /* Create OpenGL device context. Try to get an 3.2+ context if possible. */
1488 if (_wglCreateContextAttribsARB != nullptr) {
1489 /* Try for OpenGL 4.5 first. */
1490 int attribs[] = {
1491 WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
1492 WGL_CONTEXT_MINOR_VERSION_ARB, 5,
1493 WGL_CONTEXT_FLAGS_ARB, _debug_driver_level >= 8 ? WGL_CONTEXT_DEBUG_BIT_ARB : 0,
1494 _hasWGLARBCreateContextProfile ? WGL_CONTEXT_PROFILE_MASK_ARB : 0, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, // Terminate list if WGL_ARB_create_context_profile isn't supported.
1495 0
1496 };
1497 rc = _wglCreateContextAttribsARB(this->dc, nullptr, attribs);
1498
1499 if (rc == nullptr) {
1500 /* Try again for a 3.2 context. */
1501 attribs[1] = 3;
1502 attribs[3] = 2;
1503 rc = _wglCreateContextAttribsARB(this->dc, nullptr, attribs);
1504 }
1505 }
1506
1507 if (rc == nullptr) {
1508 /* Old OpenGL or old driver, let's hope for the best. */
1509 rc = wglCreateContext(this->dc);
1510 if (rc == nullptr) return "Can't create OpenGL context";
1511 }
1512 if (!wglMakeCurrent(this->dc, rc)) return "Can't active GL context";
1513
1514 this->ToggleVsync(_video_vsync);
1515
1516 this->gl_rc = rc;
1517 return OpenGLBackend::Create(&GetOGLProcAddressCallback, this->GetScreenSize());
1518}
1519
1520bool VideoDriver_Win32OpenGL::ToggleFullscreen(bool full_screen)
1521{
1522 if (_screen.dst_ptr != nullptr) this->ReleaseVideoPointer();
1523 this->DestroyContext();
1524 bool res = this->VideoDriver_Win32Base::ToggleFullscreen(full_screen);
1525 res &= this->AllocateContext() == std::nullopt;
1526 this->ClientSizeChanged(this->width, this->height, true);
1527 return res;
1528}
1529
1530bool VideoDriver_Win32OpenGL::AfterBlitterChange()
1531{
1532 assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
1533 this->ClientSizeChanged(this->width, this->height, true);
1534 return true;
1535}
1536
1537void VideoDriver_Win32OpenGL::PopulateSystemSprites()
1538{
1539 OpenGLBackend::Get()->PopulateCursorCache();
1540}
1541
1542void VideoDriver_Win32OpenGL::ClearSystemSprites()
1543{
1545}
1546
1547bool VideoDriver_Win32OpenGL::AllocateBackingStore(int w, int h, bool force)
1548{
1549 if (!force && w == _screen.width && h == _screen.height) return false;
1550
1551 this->width = w = std::max(w, 64);
1552 this->height = h = std::max(h, 64);
1553
1554 if (this->gl_rc == nullptr) return false;
1555
1556 if (_screen.dst_ptr != nullptr) this->ReleaseVideoPointer();
1557
1558 this->dirty_rect = {};
1559 bool res = OpenGLBackend::Get()->Resize(w, h, force);
1560 SwapBuffers(this->dc);
1561 _screen.dst_ptr = this->GetVideoPointer();
1562
1563 return res;
1564}
1565
1566void *VideoDriver_Win32OpenGL::GetVideoPointer()
1567{
1568 if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
1569 this->anim_buffer = OpenGLBackend::Get()->GetAnimBuffer();
1570 }
1572}
1573
1574void VideoDriver_Win32OpenGL::ReleaseVideoPointer()
1575{
1576 if (this->anim_buffer != nullptr) OpenGLBackend::Get()->ReleaseAnimBuffer(this->dirty_rect);
1577 OpenGLBackend::Get()->ReleaseVideoBuffer(this->dirty_rect);
1578 this->dirty_rect = {};
1579 _screen.dst_ptr = nullptr;
1580 this->anim_buffer = nullptr;
1581}
1582
1583void VideoDriver_Win32OpenGL::Paint()
1584{
1585 PerformanceMeasurer framerate(PFE_VIDEO);
1586
1587 if (_local_palette.count_dirty != 0) {
1589
1590 /* Always push a changed palette to OpenGL. */
1594 }
1595
1597 }
1598
1601
1602 SwapBuffers(this->dc);
1603}
1604
1605#endif /* WITH_OPENGL */
#define AS(ap_name, size_x, size_y, min_year, max_year, catchment, noise, maint_cost, ttdpatch_type, class_id, name, preview)
AirportSpec definition for airports with at least one depot.
debug_inline constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
debug_inline static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:136
How all blitters should look like.
Definition base.hpp:29
virtual uint8_t GetScreenDepth()=0
Get the screen depth this blitter works for.
virtual Blitter::PaletteAnimation UsePaletteAnimation()=0
Check if the blitter uses palette animation at all.
virtual void PaletteAnimate(const Palette &palette)=0
Called when the 8bpp palette is changed; you should redraw all pixels on the screen that are equal to...
@ None
No palette animation.
@ Blitter
The blitter takes care of the palette animation.
@ VideoBackend
Palette animation should be done by video backend (8bpp only!)
virtual void PostResize()
Post resize event.
Definition base.hpp:205
The factory for Windows' video driver.
Definition win32_v.h:110
Function GetFunction(const std::string &symbol_name)
Get a function from a loaded library.
uint current_x
Current horizontal size (after resizing).
int pos_y
Vertical position of top-left corner of the widget in the window.
int pos_x
Horizontal position of top-left corner of the widget in the window.
uint current_y
Current vertical size (after resizing).
void Paint()
Render video buffer to the screen.
Definition opengl.cpp:1037
uint8_t * GetAnimBuffer()
Get a pointer to the memory for the separate animation buffer.
Definition opengl.cpp:1168
void * GetVideoBuffer()
Get a pointer to the memory for the video driver to draw to.
Definition opengl.cpp:1146
bool Resize(int w, int h, bool force=false)
Change the size of the drawing window and allocate matching resources.
Definition opengl.cpp:911
static std::optional< std::string_view > Create(GetOGLProcAddressProc get_proc, const Dimension &screen_res)
Create and initialize the singleton back-end class.
Definition opengl.cpp:465
void UpdatePalette(const Colour *pal, uint first, uint length)
Update the stored palette.
Definition opengl.cpp:1023
void ReleaseAnimBuffer(const Rect &update_rect)
Update animation buffer texture after the animation buffer was filled.
Definition opengl.cpp:1229
void ClearCursorCache()
Queue a request for cursor cache clear.
Definition opengl.cpp:1133
static OpenGLBackend * Get()
Get singleton instance of this class.
Definition opengl.h:81
void DrawMouseCursor()
Draw mouse cursor on screen.
Definition opengl.cpp:1069
void ReleaseVideoBuffer(const Rect &update_rect)
Update video buffer texture after the video buffer was filled.
Definition opengl.cpp:1191
static void Destroy()
Free resources and destroy singleton back-end class.
Definition opengl.cpp:478
RAII class for measuring simple elements of performance.
Constant span of UTF-8 encoded data.
Definition utf8.hpp:24
Base class for Windows video drivers.
Definition win32_v.h:19
int height
Height in pixels of our display surface.
Definition win32_v.h:45
bool has_focus
Does our window have system focus?
Definition win32_v.h:42
void EditBoxLostFocus() override
An edit box lost the input focus.
Definition win32_v.cpp:1014
void CheckPaletteAnim() override
Process any pending palette animation.
Definition win32_v.cpp:926
void Stop() override
Stop this driver.
Definition win32_v.cpp:913
int height_org
Original monitor resolution height, before we changed it.
Definition win32_v.h:47
HWND main_wnd
Handle to system window.
Definition win32_v.h:40
bool fullscreen
Whether to use (true) fullscreen mode.
Definition win32_v.h:41
int width_org
Original monitor resolution width, before we changed it.
Definition win32_v.h:46
bool MakeWindow(bool full_screen, bool resize=true)
Instantiate a new window.
Definition win32_v.cpp:142
bool buffer_locked
Video buffer was locked by the main thread.
Definition win32_v.h:49
virtual void * GetVideoPointer()=0
Get a pointer to the video buffer.
void MakeDirty(int left, int top, int width, int height) override
Mark a particular area dirty.
Definition win32_v.cpp:920
bool PollEvent() override
Process a single system event.
Definition win32_v.cpp:957
virtual void PaletteChanged(HWND hWnd)=0
Palette of the window has changed.
bool LockVideoBuffer() override
Make sure the video buffer is ready for drawing.
Definition win32_v.cpp:1091
std::vector< int > GetListOfMonitorRefreshRates() override
Get a list of refresh rates of each available monitor.
Definition win32_v.cpp:1038
virtual bool AllocateBackingStore(int w, int h, bool force=false)=0
(Re-)create the backing store.
int width
Width in pixels of our display surface.
Definition win32_v.h:44
void InputLoop() override
Handle input logic, is CTRL pressed, should we fast-forward, etc.
Definition win32_v.cpp:932
virtual uint8_t GetFullscreenBpp()
Get screen depth to use for fullscreen mode.
Definition win32_v.cpp:130
Dimension GetScreenSize() const override
Get the resolution of the main screen.
Definition win32_v.cpp:1045
virtual void ReleaseVideoPointer()
Hand video buffer back to the painting backend.
Definition win32_v.h:70
void UnlockVideoBuffer() override
Unlock a previously locked video buffer.
Definition win32_v.cpp:1102
void MainLoop() override
Perform the actual drawing.
Definition win32_v.cpp:970
Rect dirty_rect
Region of the screen that needs redrawing.
Definition win32_v.h:43
float GetDPIScale() override
Get DPI scaling factor of the screen OTTD is displayed on.
Definition win32_v.cpp:1050
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
Definition win32_v.cpp:1006
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
Definition win32_v.cpp:996
The GDI video driver for windows.
Definition win32_v.h:78
void * buffer_bits
Internal rendering buffer.
Definition win32_v.h:93
HBITMAP dib_sect
System bitmap object referencing our rendering buffer.
Definition win32_v.h:91
void PaletteChanged(HWND hWnd) override
Palette of the window has changed.
Definition win32_v.cpp:1221
std::optional< std::string_view > Start(const StringList &param) override
Start this driver.
Definition win32_v.cpp:1117
void * GetVideoPointer() override
Get a pointer to the video buffer.
Definition win32_v.h:96
HPALETTE gdi_palette
Palette object for 8bpp blitter.
Definition win32_v.h:92
bool AllocateBackingStore(int w, int h, bool force=false) override
(Re-)create the backing store.
Definition win32_v.cpp:1142
void Paint() override
Paint the window.
Definition win32_v.cpp:1232
bool AfterBlitterChange() override
Callback invoked after the blitter was changed.
Definition win32_v.cpp:1180
void Stop() override
Stop this driver.
Definition win32_v.cpp:1134
bool fast_forward_key_pressed
The fast-forward key is being pressed.
void Tick()
Give the video-driver a tick.
void SleepTillNextTick()
Sleep till the next tick is about to happen.
void StartGameThread()
Start the loop for game-tick.
static std::string GetCaption()
Get the caption to use for the game's title bar.
void StopGameThread()
Stop the loop for the game-tick.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
void UpdateAutoResolution()
Apply resolution auto-detection and clamp to sensible defaults.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
std::vector< Dimension > _resolutions
List of resolutions.
Definition driver.cpp:26
Dimension _cur_resolution
The current resolution.
Definition driver.cpp:27
bool GetDriverParamBool(const StringList &parm, const char *name)
Get a boolean parameter the list of parameters.
Definition driver.cpp:65
fluid_settings_t * settings
FluidSynth settings handle.
@ PFE_VIDEO
Speed of painting drawn video buffer.
Rect BoundingRect(const Rect &r1, const Rect &r2)
Compute the bounding rectangle around two rectangles.
bool IsEmptyRect(const Rect &r)
Check if a rectangle is empty.
bool _shift_pressed
Is Shift pressed?
Definition gfx.cpp:39
bool _left_button_down
Is left mouse button pressed?
Definition gfx.cpp:41
bool _ctrl_pressed
Is Ctrl pressed?
Definition gfx.cpp:38
uint8_t _dirkeys
1 = left, 2 = up, 4 = right, 8 = down
Definition gfx.cpp:34
bool _left_button_clicked
Is left mouse button clicked?
Definition gfx.cpp:42
bool _right_button_clicked
Is right mouse button clicked?
Definition gfx.cpp:44
bool _right_button_down
Is right mouse button pressed?
Definition gfx.cpp:43
bool AdjustGUIZoom(bool automatic)
Resolve GUI zoom level and adjust GUI to new zoom, if auto-suggestion is requested.
Definition gfx.cpp:1764
void HandleCtrlChanged()
State of CONTROL key has changed.
Definition window.cpp:2629
void UpdateWindows()
Update the continuously changing contents of the windows, such as the viewports.
Definition window.cpp:3061
void GameSizeChanged()
Size of the application screen changed.
Definition main_gui.cpp:592
void HandleMouseEvents()
Handle a mouse event from the video driver.
Definition window.cpp:2890
void HandleKeypress(uint keycode, char32_t key)
Handle keyboard input.
Definition window.cpp:2573
void HandleTextInput(const char *str, bool marked=false, const char *caret=nullptr, const char *insert_location=nullptr, const char *replacement_end=nullptr)
Handle text input.
Definition window.cpp:2659
@ S8BPP_HARDWARE
Full 8bpp support by OS and hardware.
Definition gfx_type.h:372
@ WKC_BACKSLASH
\ Backslash
Definition gfx_type.h:101
@ WKC_MINUS
Definition gfx_type.h:106
@ WKC_COMMA
, Comma
Definition gfx_type.h:104
@ WKC_PERIOD
. Period
Definition gfx_type.h:105
@ WKC_EQUALS
= Equals
Definition gfx_type.h:99
@ WKC_SLASH
/ Forward slash
Definition gfx_type.h:97
@ WKC_SINGLEQUOTE
' Single quote
Definition gfx_type.h:103
@ WKC_R_BRACKET
] Right square bracket
Definition gfx_type.h:102
@ WKC_L_BRACKET
[ Left square bracket
Definition gfx_type.h:100
@ WKC_SEMICOLON
; Semicolon
Definition gfx_type.h:98
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1500
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
constexpr T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
Definition math_func.hpp:37
OpenGL video driver support.
void GetKeyboardLayout()
Retrieve keyboard layout from language string or (if set) config file.
Definition osk_gui.cpp:351
bool CopyPalette(Palette &local_palette, bool force_copy)
Copy the current palette if the palette was updated.
Definition palette.cpp:225
static OGLProc GetOGLProcAddressCallback(const char *proc)
Platform-specific callback to get an OpenGL function pointer.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:58
char32_t Utf16DecodeSurrogate(uint lead, uint trail)
Convert an UTF-16 surrogate pair to the corresponding Unicode character.
bool Utf16IsLeadSurrogate(uint c)
Is the given character a lead surrogate code point?
bool Utf16IsTrailSurrogate(uint c)
Is the given character a lead surrogate code point?
std::vector< std::string > StringList
Type for a list of strings.
Definition string_type.h:60
GUISettings gui
settings related to the GUI
bool UpdateCursorPosition(int x, int y)
Update cursor position on mouse movement.
Definition gfx.cpp:1699
bool fix_at
mouse is moving, but cursor is not (used for scrolling)
Definition gfx_type.h:129
Point pos
logical mouse position
Definition gfx_type.h:126
bool in_window
mouse inside this window, determines drawing logic
Definition gfx_type.h:148
int wheel
mouse wheel movement
Definition gfx_type.h:128
Dimensions (a width and height) of a rectangle in 2D.
uint8_t scrollwheel_multiplier
how much 'wheel' per incoming event from the OS?
Information about the currently used palette.
Definition gfx_type.h:362
int first_dirty
The first dirty element.
Definition gfx_type.h:364
int count_dirty
The number of dirty elements.
Definition gfx_type.h:365
Colour palette[256]
Current palette. Entry 0 has to be always fully transparent!
Definition gfx_type.h:363
Coordinates of a point in 2D.
Specification of a rectangle with absolute coordinates of all edges.
WindowClass window_class
Window class.
Definition window_gui.h:302
virtual Point GetCaretPosition() const
Get the current caret position if an edit box has the focus.
Definition window.cpp:377
int left
x position of left edge of the window
Definition window_gui.h:310
const NWidgetCore * nested_focus
Currently focused nested widget, or nullptr if no nested widget has focus.
Definition window_gui.h:320
int top
y position of top edge of the window
Definition window_gui.h:311
int height
Height of the window (number of pixels down in y direction)
Definition window_gui.h:313
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:312
bool _video_vsync
Whether we should use vsync (only if active video driver supports HW acceleration).
std::wstring OTTD2FS(const std::string &name)
Convert from OpenTTD's encoding to a wide string.
Definition win32.cpp:354
char * convert_from_fs(const std::wstring_view src, std::span< char > dst_buf)
Convert to OpenTTD's encoding from that of the environment in UNICODE.
Definition win32.cpp:372
std::string FS2OTTD(const std::wstring &name)
Convert to OpenTTD's encoding from a wide string.
Definition win32.cpp:337
static Palette _local_palette
Current palette to use for drawing.
Definition win32_v.cpp:54
static LRESULT HandleCharMsg(uint keycode, char32_t charcode)
Forward key presses to the window system.
Definition win32_v.cpp:246
static bool DrawIMECompositionString()
Should we draw the composition string ourself, i.e is this a normal IME?
Definition win32_v.cpp:273
static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
Handle WM_IME_COMPOSITION messages.
Definition win32_v.cpp:335
static void SetCandidatePos(HWND hwnd)
Set the position of the candidate window.
Definition win32_v.cpp:301
static void CancelIMEComposition(HWND hwnd)
Clear the current composition string.
Definition win32_v.cpp:397
static void SetCompositionPos(HWND hwnd)
Set position of the composition window to the caret position.
Definition win32_v.cpp:279
Base of the Windows video driver.
void ReInitAllWindows(bool zoom_changed)
Re-initialize all windows.
Definition window.cpp:3340
bool EditBoxInGlobalFocus()
Check if an edit box is in global focus.
Definition window.cpp:447
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3241
@ WC_CONSOLE
Console; Window numbers:
@ WC_GAME_OPTIONS
Game options window; Window numbers: