OpenTTD Source: src/video/win32_v.cpp Source File

OpenTTD Source 15.0-RC2

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