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

OpenTTD Source 14.0-RC3

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