31#include <versionhelpers.h>
32#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
33#include <winrt/Windows.UI.ViewManagement.h>
38#include "../3rdparty/opengl/glext.h"
39#include "../3rdparty/opengl/wglext.h"
46#ifndef MAPVK_VK_TO_CHAR
47#define MAPVK_VK_TO_CHAR (2)
51#define PM_QS_INPUT 0x20000
55#define WM_DPICHANGED 0x02E0
64 MyShowCursor(
false,
true);
73#define AS(x, z) {x, 1, z}
74#define AM(x, y, z, w) {x, y - x + 1, z}
78 AM(VK_PRIOR, VK_DOWN, WKC_PAGEUP, WKC_DOWN),
80 AM(
'A',
'Z',
'A',
'Z'),
81 AM(
'0',
'9',
'0',
'9'),
83 AS(VK_ESCAPE, WKC_ESC),
84 AS(VK_PAUSE, WKC_PAUSE),
85 AS(VK_BACK, WKC_BACKSPACE),
86 AM(VK_INSERT, VK_DELETE, WKC_INSERT, WKC_DELETE),
88 AS(VK_SPACE, WKC_SPACE),
89 AS(VK_RETURN, WKC_RETURN),
93 AM(VK_F1, VK_F12, WKC_F1, WKC_F12),
96 AM(VK_NUMPAD0, VK_NUMPAD9,
'0',
'9'),
97 AS(VK_DIVIDE, WKC_NUM_DIV),
98 AS(VK_MULTIPLY, WKC_NUM_MUL),
99 AS(VK_SUBTRACT, WKC_NUM_MINUS),
100 AS(VK_ADD, WKC_NUM_PLUS),
101 AS(VK_DECIMAL, WKC_NUM_DECIMAL),
117static uint MapWindowsKey(uint sym)
121 for (
const auto &map : _vk_mapping) {
122 if (
IsInsideBS(sym, map.vk_from, map.vk_count)) {
123 key = sym - map.vk_from + map.map_to;
128 if (GetAsyncKeyState(VK_SHIFT) < 0) key |= WKC_SHIFT;
129 if (GetAsyncKeyState(VK_CONTROL) < 0) key |= WKC_CTRL;
130 if (GetAsyncKeyState(VK_MENU) < 0) key |= WKC_ALT;
154 _fullscreen = full_screen;
174 if (
settings.dmBitsPerPel == 8 && ChangeDisplaySettings(&
settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
179 if (ChangeDisplaySettings(&
settings, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) {
181 GetWindowRect(GetDesktopWindow(), &r);
184 if ((
int)
settings.dmPelsWidth != r.right - r.left || (
int)
settings.dmPelsHeight != r.bottom - r.top) {
189 if (ChangeDisplaySettings(&
settings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) {
195 ChangeDisplaySettings(
nullptr, 0);
197 this->
width = _bck_resolution.width;
198 this->
height = _bck_resolution.height;
203 DWORD style, showstyle;
206 showstyle = SW_SHOWNORMAL;
212 style = WS_OVERLAPPEDWINDOW;
218 AdjustWindowRect(&r, style, FALSE);
219 w = r.right - r.left;
220 h = r.bottom - r.top;
223 if (!
_window_maximize && resize) SetWindowPos(this->
main_wnd, 0, 0, 0, w, h, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOMOVE);
231 mi.cbSize =
sizeof(mi);
232 GetMonitorInfo(MonitorFromWindow(0, MONITOR_DEFAULTTOPRIMARY), &mi);
234 x = (mi.rcWork.right - mi.rcWork.left - w) / 2;
235 y = (mi.rcWork.bottom - mi.rcWork.top - h) / 2;
239 this->
main_wnd = CreateWindow(L
"OTTD",
OTTD2FS(caption).c_str(), style, x, y, w, h, 0, 0, GetModuleHandle(
nullptr),
this);
240 if (this->
main_wnd ==
nullptr) UserError(
"CreateWindow failed");
241 ShowWindow(this->
main_wnd, showstyle);
259 static char32_t prev_char = 0;
264 prev_char = charcode;
269 if (prev_char != 0) {
289 return (_imm_props & IME_PROP_AT_CARET) && !(_imm_props & IME_PROP_SPECIAL_UI);
298 HIMC hIMC = ImmGetContext(hwnd);
299 if (hIMC !=
nullptr) {
301 cf.dwStyle = CFS_POINT;
309 cf.ptCurrentPos.x = 0;
310 cf.ptCurrentPos.y = 0;
312 ImmSetCompositionWindow(hIMC, &cf);
314 ImmReleaseContext(hwnd, hIMC);
323 HIMC hIMC = ImmGetContext(hwnd);
324 if (hIMC !=
nullptr) {
327 cf.dwStyle = CFS_EXCLUDE;
341 cf.rcArea.right = cf.rcArea.left +
_focused_window->nested_focus->current_x;
342 cf.rcArea.bottom = cf.rcArea.top +
_focused_window->nested_focus->current_y;
345 cf.ptCurrentPos.x = 0;
346 cf.ptCurrentPos.y = 0;
347 SetRectEmpty(&cf.rcArea);
349 ImmSetCandidateWindow(hIMC, &cf);
351 ImmReleaseContext(hwnd, hIMC);
363 HIMC hIMC = ImmGetContext(hwnd);
365 if (hIMC !=
nullptr) {
366 if (lParam & GCS_RESULTSTR) {
368 LONG len = ImmGetCompositionString(hIMC, GCS_RESULTSTR,
nullptr, 0);
369 std::wstring str(len + 1, L
'\0');
370 len = ImmGetCompositionString(hIMC, GCS_RESULTSTR, str.data(), len);
371 str[len /
sizeof(wchar_t)] = L
'\0';
381 lParam &= ~(GCS_RESULTSTR | GCS_RESULTCLAUSE | GCS_RESULTREADCLAUSE | GCS_RESULTREADSTR);
386 LONG len = ImmGetCompositionString(hIMC, GCS_COMPSTR,
nullptr, 0);
387 std::wstring str(len + 1, L
'\0');
388 len = ImmGetCompositionString(hIMC, GCS_COMPSTR, str.data(), len);
389 str[len /
sizeof(wchar_t)] = L
'\0';
392 static char utf8_buf[1024];
396 LONG caret_bytes = ImmGetCompositionString(hIMC, GCS_CURSORPOS,
nullptr, 0);
398 auto caret = view.begin();
399 const auto end = view.end();
400 for (
const wchar_t *c = str.c_str(); *c !=
'\0' && caret != end && caret_bytes > 0; c++, caret_bytes--) {
414 lParam &= ~(GCS_COMPSTR | GCS_COMPATTR | GCS_COMPCLAUSE | GCS_CURSORPOS | GCS_DELTASTART);
417 ImmReleaseContext(hwnd, hIMC);
419 return lParam != 0 ? DefWindowProc(hwnd, WM_IME_COMPOSITION, wParam, lParam) : 0;
428 HIMC hIMC = ImmGetContext(hwnd);
429 if (hIMC !=
nullptr) ImmNotifyIME(hIMC, NI_COMPOSITIONSTR, CPS_CANCEL, 0);
430 ImmReleaseContext(hwnd, hIMC);
435#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
443extern "C" int32_t __stdcall WINRT_IMPL_RoOriginateLanguageException(int32_t error,
void *message,
void *languageException)
noexcept
445 typedef BOOL(WINAPI *PFNRoOriginateLanguageException)(int32_t,
void *,
void *);
446 static PFNRoOriginateLanguageException RoOriginateLanguageException = _combase.GetFunction(
"RoOriginateLanguageException");
448 if (RoOriginateLanguageException !=
nullptr) {
449 return RoOriginateLanguageException(error, message, languageException);
455extern "C" int32_t __stdcall WINRT_IMPL_RoGetActivationFactory(
void *classId, winrt::guid
const &iid,
void **factory)
noexcept
457 typedef BOOL(WINAPI *PFNRoGetActivationFactory)(
void *, winrt::guid
const &,
void **);
458 static PFNRoGetActivationFactory RoGetActivationFactory = _combase.GetFunction(
"RoGetActivationFactory");
460 if (RoGetActivationFactory !=
nullptr) {
461 return RoGetActivationFactory(classId, iid, factory);
464 return winrt::impl::error_class_not_available;
469static bool IsDarkModeEnabled()
472#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
473 if (IsWindows10OrGreater()) {
483 winrt::Windows::UI::ViewManagement::UISettings
settings;
484 auto foreground =
settings.GetColorValue(winrt::Windows::UI::ViewManagement::UIColorType::Foreground);
487 return ((5 * foreground.G) + (2 * foreground.R) + foreground.B) > (8 * 128);
498static void SetDarkModeForWindow(HWND hWnd,
bool dark_mode)
501#if defined(NTDDI_WIN10)
502 if (!IsWindows10OrGreater())
return;
507 typedef HRESULT(WINAPI *PFNDWMSETWINDOWATTRIBUTE)(HWND, DWORD, LPCVOID, DWORD);
508 static const PFNDWMSETWINDOWATTRIBUTE DwmSetWindowAttribute = _dwmapi.GetFunction(
"DwmSetWindowAttribute");
510 if (DwmSetWindowAttribute !=
nullptr) {
514 BOOL value = dark_mode ? TRUE : FALSE;
515 if (DwmSetWindowAttribute(hWnd, 20 , &value,
sizeof(value)) != S_OK) {
516 DwmSetWindowAttribute(hWnd, 19 , &value,
sizeof(value));
522LRESULT CALLBACK WndProcGdi(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
524 static uint32_t keycode = 0;
525 static bool console =
false;
527 const float SCROLL_BUILTIN_MULTIPLIER = 14.0f / WHEEL_DELTA;
533 SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)((LPCREATESTRUCT)lParam)->lpCreateParams);
534 _cursor.in_window =
false;
539 SetDarkModeForWindow(hwnd, IsDarkModeEnabled());
542 case WM_SETTINGCHANGE:
544 SetDarkModeForWindow(hwnd, IsDarkModeEnabled());
549 GetUpdateRect(hwnd, &r, FALSE);
550 video_driver->
MakeDirty(r.left, r.top, r.right - r.left, r.bottom - r.top);
552 ValidateRect(hwnd,
nullptr);
556 case WM_PALETTECHANGED:
557 if ((HWND)wParam == hwnd)
return 0;
560 case WM_QUERYNEWPALETTE:
565 HandleExitGameRequest();
613 if ((wParam & MK_XBUTTON1) != 0) {
618 if ((wParam & MK_XBUTTON2) != 0) {
627 if ((wParam & MK_XBUTTON1) == 0) {
631 if ((wParam & MK_XBUTTON2) == 0) {
639 _cursor.in_window =
false;
641 if (!
_input_pressed.Any({ControlInput::Left, ControlInput::Right})) MyShowCursor(
true);
645 int x = (int16_t)LOWORD(lParam);
646 int y = (int16_t)HIWORD(lParam);
651 if (!_cursor.in_window) {
652 _cursor.in_window =
true;
654 tme.cbSize =
sizeof(tme);
655 tme.dwFlags = TME_LEAVE;
656 tme.hwndTrack = hwnd;
658 TrackMouseEvent(&tme);
661 if (_cursor.fix_at) {
665 while (PeekMessage(&m, hwnd, WM_MOUSEMOVE, WM_MOUSEMOVE, PM_REMOVE | PM_NOYIELD | PM_QS_INPUT)) {
666 x = (int16_t)LOWORD(m.lParam);
667 y = (int16_t)HIWORD(m.lParam);
671 if (_cursor.UpdateCursorPosition(x, y)) {
673 pt.x = _cursor.pos.x;
674 pt.y = _cursor.pos.y;
675 ClientToScreen(hwnd, &pt);
676 SetCursorPos(pt.x, pt.y);
683 case WM_INPUTLANGCHANGE:
687 case WM_IME_SETCONTEXT:
692 case WM_IME_STARTCOMPOSITION:
697 case WM_IME_COMPOSITION:
700 case WM_IME_ENDCOMPOSITION:
711 console =
GB(lParam, 16, 8) == 41;
715 uint scancode =
GB(lParam, 16, 8);
716 uint charcode = wParam;
720 if (console && scancode == 41) {
727 uint cur_keycode = keycode;
735 uint scancode =
GB(lParam, 16, 8);
736 keycode = scancode == 41 ? (uint)WKC_BACKQUOTE : MapWindowsKey(wParam);
738 uint charcode = MapVirtualKey(wParam, MAPVK_VK_TO_CHAR);
749 if (
HasBit(charcode, 31) && !console) {
750 if (scancode == 41) {
759 uint cur_keycode = keycode;
789 if (wParam != SIZE_MINIMIZED) {
799 RECT *r = (RECT*)lParam;
803 SetRect(&r2, 0, 0, 0, 0);
804 AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
806 w = r->right - r->left - (r2.right - r2.left);
807 h = r->bottom - r->top - (r2.bottom - r2.top);
810 SetRect(&r2, 0, 0, w, h);
812 AdjustWindowRect(&r2, GetWindowLong(hwnd, GWL_STYLE), FALSE);
813 w = r2.right - r2.left;
814 h = r2.bottom - r2.top;
818 r->bottom = r->top + h;
821 case WMSZ_BOTTOMLEFT:
822 r->bottom = r->top + h;
823 r->left = r->right - w;
826 case WMSZ_BOTTOMRIGHT:
827 r->bottom = r->top + h;
828 r->right = r->left + w;
832 r->left = r->right - w;
836 r->right = r->left + w;
840 r->top = r->bottom - h;
844 r->top = r->bottom - h;
845 r->left = r->right - w;
849 r->top = r->bottom - h;
850 r->right = r->left + w;
856 case WM_DPICHANGED: {
860 RECT *prcNewWindow = (RECT *)lParam;
865 prcNewWindow->right - prcNewWindow->left,
866 prcNewWindow->bottom - prcNewWindow->top,
867 SWP_NOZORDER | SWP_NOACTIVATE);
875#if !defined(WM_MOUSEWHEEL)
876# define WM_MOUSEWHEEL 0x020A
878#if !defined(WM_MOUSEHWHEEL)
879# define WM_MOUSEHWHEEL 0x020E
881#if !defined(GET_WHEEL_DELTA_WPARAM)
882# define GET_WHEEL_DELTA_WPARAM(wparam) ((short)HIWORD(wparam))
885 case WM_MOUSEWHEEL: {
886 int delta = GET_WHEEL_DELTA_WPARAM(wParam);
890 }
else if (delta > 0) {
894 _cursor.v_wheel -=
static_cast<float>(delta) * SCROLL_BUILTIN_MULTIPLIER *
_settings_client.gui.scrollwheel_multiplier;
895 _cursor.wheel_moved =
true;
900 case WM_MOUSEHWHEEL: {
901 int delta = GET_WHEEL_DELTA_WPARAM(wParam);
903 _cursor.h_wheel +=
static_cast<float>(delta) * SCROLL_BUILTIN_MULTIPLIER *
_settings_client.gui.scrollwheel_multiplier;
904 _cursor.wheel_moved =
true;
920 if (_exit_game)
break;
922 bool active = (LOWORD(wParam) != WA_INACTIVE);
923 bool minimized = (HIWORD(wParam) != 0);
925 if (active && minimized) {
928 ShowWindow(hwnd, SW_RESTORE);
935 }
else if (!active && !minimized) {
941 ShowWindow(hwnd, SW_MINIMIZE);
949 return DefWindowProc(hwnd, msg, wParam, lParam);
952static void RegisterWndClass()
954 static bool registered =
false;
956 if (registered)
return;
958 HINSTANCE hinst = GetModuleHandle(
nullptr);
965 LoadIcon(hinst, MAKEINTRESOURCE(100)),
966 LoadCursor(
nullptr, IDC_ARROW),
973 if (!RegisterClass(&wnd)) UserError(
"RegisterClass failed");
976static const Dimension default_resolutions[] = {
995 for (uint i = 0; EnumDisplaySettings(
nullptr, i, &dm) != 0; i++) {
996 if (dm.dmBitsPerPel != bpp || dm.dmPelsWidth < 640 || dm.dmPelsHeight < 480)
continue;
998 _resolutions.emplace_back(dm.dmPelsWidth, dm.dmPelsHeight);
1003 _resolutions.assign(std::begin(default_resolutions), std::end(default_resolutions));
1009std::optional<std::string_view> VideoDriver_Win32Base::Initialize()
1012 if (FAILED(CoInitializeEx(
nullptr, COINIT_MULTITHREADED)))
return "COM initialization failed";
1024 return std::nullopt;
1043 this->
MakeDirty(0, 0, _screen.width, _screen.height);
1074 if (!PeekMessage(&mesg,
nullptr, 0, 0, PM_REMOVE))
return false;
1078 DispatchMessage(&mesg);
1088 if (_exit_game)
break;
1140static BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM data)
1142 auto &list = *
reinterpret_cast<std::vector<int>*
>(data);
1144 MONITORINFOEX monitorInfo = {};
1145 monitorInfo.cbSize =
sizeof(MONITORINFOEX);
1146 GetMonitorInfo(hMonitor, &monitorInfo);
1148 DEVMODE devMode = {};
1149 devMode.dmSize =
sizeof(DEVMODE);
1150 devMode.dmDriverExtra = 0;
1151 EnumDisplaySettings(monitorInfo.szDevice, ENUM_CURRENT_SETTINGS, &devMode);
1153 if (devMode.dmDisplayFrequency != 0) list.push_back(devMode.dmDisplayFrequency);
1159 std::vector<int> rates = {};
1160 EnumDisplayMonitors(
nullptr,
nullptr, MonitorEnumProc,
reinterpret_cast<LPARAM
>(&rates));
1166 return {
static_cast<uint
>(GetSystemMetrics(SM_CXSCREEN)),
static_cast<uint
>(GetSystemMetrics(SM_CYSCREEN)) };
1175 assert(_screen.dst_ptr !=
nullptr);
1182 assert(_screen.dst_ptr !=
nullptr);
1183 if (_screen.dst_ptr !=
nullptr) {
1186 _screen.dst_ptr =
nullptr;
1199 auto err = this->Initialize();
1200 if (err)
return err;
1202 this->MakePalette();
1210 return std::nullopt;
1225 w = std::max(w, 64);
1226 h = std::max(h, 64);
1228 if (!force && w == _screen.width && h == _screen.height)
return false;
1230 BITMAPINFO *bi = (BITMAPINFO *)
new char[
sizeof(BITMAPINFOHEADER) +
sizeof(RGBQUAD) * 256]();
1231 bi->bmiHeader.biSize =
sizeof(BITMAPINFOHEADER);
1233 bi->bmiHeader.biWidth = this->
width = w;
1234 bi->bmiHeader.biHeight = -(this->
height = h);
1236 bi->bmiHeader.biPlanes = 1;
1237 bi->bmiHeader.biBitCount = bpp;
1238 bi->bmiHeader.biCompression = BI_RGB;
1243 this->
dib_sect = CreateDIBSection(dc, bi, DIB_RGB_COLORS, (VOID **)&this->
buffer_bits,
nullptr, 0);
1246 UserError(
"CreateDIBSection failed");
1251 _screen.pitch = (bpp == 8) ?
Align(w, 4) : w;
1265void VideoDriver_Win32GDI::MakePalette()
1269 LOGPALETTE *pal = (LOGPALETTE *)
new char[
sizeof(LOGPALETTE) + (256 - 1) *
sizeof(PALETTEENTRY)]();
1271 pal->palVersion = 0x300;
1272 pal->palNumEntries = 256;
1274 for (uint i = 0; i != 256; i++) {
1278 pal->palPalEntry[i].peFlags = 0;
1283 if (this->
gdi_palette ==
nullptr) UserError(
"CreatePalette failed!\n");
1286void VideoDriver_Win32GDI::UpdatePalette(HDC dc, uint start, uint count)
1290 for (uint i = 0; i != count; i++) {
1294 rgb[i].rgbReserved = 0;
1297 SetDIBColorTable(dc, start, count, rgb);
1302 HDC hDC = GetWindowDC(hWnd);
1303 HPALETTE hOldPalette = SelectPalette(hDC, this->
gdi_palette, FALSE);
1304 UINT nChanged = RealizePalette(hDC);
1306 SelectPalette(hDC, hOldPalette, TRUE);
1307 ReleaseDC(hWnd, hDC);
1308 if (nChanged != 0) this->
MakeDirty(0, 0, _screen.width, _screen.height);
1318 HDC dc2 = CreateCompatibleDC(dc);
1320 HBITMAP old_bmp = (HBITMAP)SelectObject(dc2, this->
dib_sect);
1321 HPALETTE old_palette = SelectPalette(dc, this->
gdi_palette, FALSE);
1328 this->UpdatePalette(dc2, this->
local_palette.first_dirty, this->local_palette.count_dirty);
1345 BitBlt(dc, 0, 0, this->
width, this->
height, dc2, 0, 0, SRCCOPY);
1346 SelectPalette(dc, old_palette, TRUE);
1347 SelectObject(dc2, old_bmp);
1358 int VideoDriver_Win32GDI::RedrawScreenDebug()
1376#ifndef PFD_SUPPORT_COMPOSITION
1377# define PFD_SUPPORT_COMPOSITION 0x00008000
1380static PFNWGLCREATECONTEXTATTRIBSARBPROC _wglCreateContextAttribsARB =
nullptr;
1381static PFNWGLSWAPINTERVALEXTPROC _wglSwapIntervalEXT =
nullptr;
1382static bool _hasWGLARBCreateContextProfile =
false;
1391 OGLProc ret =
reinterpret_cast<OGLProc
>(wglGetProcAddress(proc));
1392 if (ret ==
nullptr) {
1394 ret =
reinterpret_cast<OGLProc
>(GetProcAddress(GetModuleHandle(L
"opengl32"), proc));
1404static std::optional<std::string_view> SelectPixelFormat(HDC dc)
1406 PIXELFORMATDESCRIPTOR pfd = {
1407 sizeof(PIXELFORMATDESCRIPTOR),
1409 PFD_DRAW_TO_WINDOW |
1410 PFD_SUPPORT_OPENGL |
1415 0, 0, 0, 0, 0, 0, 0, 0,
1423 pfd.dwFlags |= PFD_SUPPORT_COMPOSITION;
1426 int format = ChoosePixelFormat(dc, &pfd);
1427 if (format == 0)
return "No suitable pixel format found";
1428 if (!SetPixelFormat(dc, format, &pfd))
return "Can't set pixel format";
1430 return std::nullopt;
1434static void LoadWGLExtensions()
1441 HWND wnd = CreateWindow(L
"STATIC", L
"dummy", WS_OVERLAPPEDWINDOW, 0, 0, 0, 0,
nullptr,
nullptr, GetModuleHandle(
nullptr),
nullptr);
1442 HDC dc = GetDC(wnd);
1445 if (SelectPixelFormat(dc) == std::nullopt) {
1447 HGLRC rc = wglCreateContext(dc);
1448 if (rc !=
nullptr) {
1449 wglMakeCurrent(dc, rc);
1453#pragma GCC diagnostic push
1454#pragma GCC diagnostic ignored "-Wcast-function-type"
1458 PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress(
"wglGetExtensionsStringARB");
1459 if (wglGetExtensionsStringARB !=
nullptr) {
1460 std::string_view wgl_exts = wglGetExtensionsStringARB(dc);
1463 _wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress(
"wglCreateContextAttribsARB");
1467 _wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress(
"wglSwapIntervalEXT");
1472#pragma GCC diagnostic pop
1474 wglMakeCurrent(
nullptr,
nullptr);
1475 wglDeleteContext(rc);
1483static FVideoDriver_Win32OpenGL iFVideoDriver_Win32OpenGL;
1485std::optional<std::string_view> VideoDriver_Win32OpenGL::Start(
const StringList ¶m)
1491 LoadWGLExtensions();
1493 auto err = this->Initialize();
1499 this->MakeWindow(_fullscreen);
1502 err = this->AllocateContext();
1509 this->driver_info = GetName();
1510 this->driver_info +=
" (";
1512 this->driver_info +=
")";
1514 this->ClientSizeChanged(this->width, this->height,
true);
1516 if (_screen.dst_ptr ==
nullptr) {
1519 return "Can't get pointer to screen buffer";
1522 this->ReleaseVideoPointer();
1528 return std::nullopt;
1531void VideoDriver_Win32OpenGL::Stop()
1533 this->DestroyContext();
1537void VideoDriver_Win32OpenGL::DestroyContext()
1541 wglMakeCurrent(
nullptr,
nullptr);
1542 if (this->gl_rc !=
nullptr) {
1543 wglDeleteContext(this->gl_rc);
1544 this->gl_rc =
nullptr;
1546 if (this->dc !=
nullptr) {
1547 ReleaseDC(this->main_wnd, this->dc);
1552void VideoDriver_Win32OpenGL::ToggleVsync(
bool vsync)
1554 if (_wglSwapIntervalEXT !=
nullptr) {
1555 _wglSwapIntervalEXT(vsync);
1561std::optional<std::string_view> VideoDriver_Win32OpenGL::AllocateContext()
1563 this->dc = GetDC(this->main_wnd);
1565 auto err = SelectPixelFormat(this->dc);
1566 if (err)
return err;
1571 if (_wglCreateContextAttribsARB !=
nullptr) {
1574 WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
1575 WGL_CONTEXT_MINOR_VERSION_ARB, 5,
1577 _hasWGLARBCreateContextProfile ? WGL_CONTEXT_PROFILE_MASK_ARB : 0, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
1580 rc = _wglCreateContextAttribsARB(this->dc,
nullptr, attribs);
1582 if (rc ==
nullptr) {
1586 rc = _wglCreateContextAttribsARB(this->dc,
nullptr, attribs);
1590 if (rc ==
nullptr) {
1592 rc = wglCreateContext(this->dc);
1593 if (rc ==
nullptr)
return "Can't create OpenGL context";
1595 if (!wglMakeCurrent(this->dc, rc))
return "Can't activate GL context";
1603bool VideoDriver_Win32OpenGL::ToggleFullscreen(
bool full_screen)
1605 if (_screen.dst_ptr !=
nullptr) this->ReleaseVideoPointer();
1606 this->DestroyContext();
1608 res &= this->AllocateContext() == std::nullopt;
1609 this->ClientSizeChanged(this->width, this->height,
true);
1613bool VideoDriver_Win32OpenGL::AfterBlitterChange()
1616 this->ClientSizeChanged(this->width, this->height,
true);
1620void VideoDriver_Win32OpenGL::PopulateSystemSprites()
1625void VideoDriver_Win32OpenGL::ClearSystemSprites()
1630bool VideoDriver_Win32OpenGL::AllocateBackingStore(
int w,
int h,
bool force)
1632 if (!force && w == _screen.width && h == _screen.height)
return false;
1634 this->width = w = std::max(w, 64);
1635 this->height = h = std::max(h, 64);
1637 if (this->gl_rc ==
nullptr)
return false;
1639 if (_screen.dst_ptr !=
nullptr) this->ReleaseVideoPointer();
1641 this->dirty_rect = {};
1643 SwapBuffers(this->dc);
1644 _screen.dst_ptr = this->GetVideoPointer();
1649void *VideoDriver_Win32OpenGL::GetVideoPointer()
1653 this->anim_pitch = _screen.pitch;
1658void VideoDriver_Win32OpenGL::ReleaseVideoPointer()
1662 this->dirty_rect = {};
1663 _screen.dst_ptr =
nullptr;
1664 this->anim_buffer =
nullptr;
1665 this->anim_pitch = 0;
1668void VideoDriver_Win32OpenGL::Paint()
1672 if (this->local_palette.count_dirty != 0) {
1681 this->local_palette.count_dirty = 0;
1687 SwapBuffers(this->dc);
#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.
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
How all blitters should look like.
virtual uint8_t GetScreenDepth()=0
Get the screen depth this blitter works for.
virtual Blitter::PaletteAnimation UsePaletteAnimation()=0
Check if the blitter uses palette animation at all.
virtual void PaletteAnimate(const Palette &palette)=0
Called when the 8bpp palette is changed; you should redraw all pixels on the screen that are equal to...
@ None
No palette animation.
@ Blitter
The blitter takes care of the palette animation.
@ VideoBackend
Palette animation should be done by video backend (8bpp only!).
virtual void PostResize()
Post resize event.
The factory for Windows' video driver.
void Paint()
Render video buffer to the screen.
uint8_t * GetAnimBuffer()
Get a pointer to the memory for the separate animation buffer.
void * GetVideoBuffer()
Get a pointer to the memory for the video driver to draw to.
bool Resize(int w, int h, bool force=false)
Change the size of the drawing window and allocate matching resources.
static std::optional< std::string_view > Create(GetOGLProcAddressProc get_proc, const Dimension &screen_res)
Create and initialize the singleton back-end class.
void UpdatePalette(const Colour *pal, uint first, uint length)
Update the stored palette.
void ReleaseAnimBuffer(const Rect &update_rect)
Update animation buffer texture after the animation buffer was filled.
void ClearCursorCache()
Queue a request for cursor cache clear.
static OpenGLBackend * Get()
Get singleton instance of this class.
void DrawMouseCursor()
Draw mouse cursor on screen.
void ReleaseVideoBuffer(const Rect &update_rect)
Update video buffer texture after the video buffer was filled.
static void Destroy()
Free resources and destroy singleton back-end class.
Constant span of UTF-8 encoded data.
Base class for Windows video drivers.
int height
Height in pixels of our display surface.
bool has_focus
Does our window have system focus?
void EditBoxLostFocus() override
An edit box lost the input focus.
void CheckPaletteAnim() override
Process any pending palette animation.
void Stop() override
Stop this driver.
int height_org
Original monitor resolution height, before we changed it.
HWND main_wnd
Handle to system window.
bool fullscreen
Whether to use (true) fullscreen mode.
int width_org
Original monitor resolution width, before we changed it.
bool MakeWindow(bool full_screen, bool resize=true)
Instantiate a new window.
bool buffer_locked
Video buffer was locked by the main thread.
virtual void * GetVideoPointer()=0
Get a pointer to the video buffer.
void MakeDirty(int left, int top, int width, int height) override
Mark a particular area dirty.
bool PollEvent() override
Process a single system event.
virtual void PaletteChanged(HWND hWnd)=0
Palette of the window has changed.
bool LockVideoBuffer() override
Make sure the video buffer is ready for drawing.
std::vector< int > GetListOfMonitorRefreshRates() override
Get a list of refresh rates of each available monitor.
virtual bool AllocateBackingStore(int w, int h, bool force=false)=0
(Re-)create the backing store.
int width
Width in pixels of our display surface.
void InputLoop() override
Handle input logic, is CTRL pressed, should we fast-forward, etc.
virtual uint8_t GetFullscreenBpp()
Colour depth to use for fullscreen display modes.
Dimension GetScreenSize() const override
Get the resolution of the main screen.
virtual void ReleaseVideoPointer()
Hand video buffer back to the painting backend.
Palette local_palette
Current palette to use for drawing.
void UnlockVideoBuffer() override
Unlock a previously locked video buffer.
virtual bool MinimiseRestoreWithToggleFullscreen() const
Whether minimising and restoring fullscreen windows uses ToggleFullscreen.
void ClientSizeChanged(int w, int h, bool force=false)
Indicate to the driver the client-size might have changed.
void MainLoop() override
Perform the actual drawing.
void ClaimMousePointer() override
Claim the exclusive rights for the mouse pointer.
Rect dirty_rect
Region of the screen that needs redrawing.
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
The GDI video driver for windows.
void * buffer_bits
Internal rendering buffer.
HBITMAP dib_sect
System bitmap object referencing our rendering buffer.
void PaletteChanged(HWND hWnd) override
Palette of the window has changed.
std::optional< std::string_view > Start(const StringList ¶m) override
Start this driver.
void * GetVideoPointer() override
Get a pointer to the video buffer.
HPALETTE gdi_palette
Palette object for 8bpp blitter.
bool AllocateBackingStore(int w, int h, bool force=false) override
(Re-)create the backing store.
void Paint() override
Paint the window.
bool AfterBlitterChange() override
Callback invoked after the blitter was changed.
void Stop() override
Stop this driver.
bool fast_forward_key_pressed
The fast-forward key is being pressed.
void Tick()
Give the video-driver a tick.
void SleepTillNextTick()
Sleep till the next tick is about to happen.
void StartGameThread()
Start the loop for game-tick.
static std::string GetCaption()
Get the caption to use for the game's title bar.
void StopGameThread()
Stop the loop for the game-tick.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
void UpdateAutoResolution()
Apply resolution auto-detection and clamp to sensible defaults.
bool is_game_threaded
Whether the game is allowed to use threads; cleared in the driver implementation constructors if requ...
static OGLProc GetOGLProcAddressCallback(const char *proc)
Platform-specific callback to get an OpenGL function pointer.
bool _window_maximize
Declared in win32_v.cpp.
bool IsVisibleSeverity(Facility facility, Severity severity)
Test if debug severity is visible for the given facility.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
@ Driver
Driver message facility.
@ Warning
Warning, wrong but okay if you don't know.
@ Critical
Critical, user should know about this.
@ Trace2
Trace information #2.
@ Error
Error, but we are recovering.
bool GetDriverParamBool(const StringList &parm, std::string_view name)
Get a boolean parameter the list of parameters.
std::vector< Dimension > _resolutions
List of resolutions.
Dimension _cur_resolution
The current resolution.
Error reporting related functions.
Factory to 'query' all available blitters.
fluid_settings_t * settings
FluidSynth settings handle.
Types for recording game performance data.
@ Video
Speed of painting drawn video buffer.
Rect BoundingRect(const Rect &r1, const Rect &r2)
Compute the bounding rectangle around two rectangles.
bool IsEmptyRect(const Rect &r)
Check if a rectangle is empty.
ControlInputs _input_pressed
Control inputs that are currently pressed.
ControlInputs _input_clicked
Control inputs that have been actioned.
Support8bpp _support8bpp
State of the support for 8bpp graphics.
DirectionKeys _dirkeys
Pressed direction keys.
bool AdjustGUIZoom(bool automatic)
Resolve GUI zoom level and adjust GUI to new zoom, if auto-suggestion is requested.
Functions related to the gfx engine.
void HandleCtrlChanged()
State of CONTROL key has changed.
void UpdateWindows()
Update the continuously changing contents of the windows, such as the viewports.
void GameSizeChanged()
Size of the application screen changed.
void HandleMouseEvents()
Handle a mouse event from the video driver.
bool IsCtrlPressed()
Test if the ctrl key is pressed.
void HandleKeypress(uint keycode, char32_t key)
Handle keyboard input.
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.
@ Hardware
Full 8bpp support by OS and hardware.
@ Ctrl
Ctrl modifier is pressed.
@ X2
X2 mouse button is pressed.
@ Shift
Shift modifier is pressed.
@ Right
Right mouse button is pressed.
@ Left
Left mouse button is pressed.
@ Middle
Middle mouse button is pressed.
@ X1
X1 mouse button is pressed.
@ WKC_BACKSLASH
\ Backslash
@ WKC_SLASH
/ Forward slash
@ WKC_SINGLEQUOTE
' Single quote
@ WKC_R_BRACKET
] Right square bracket
@ WKC_L_BRACKET
[ Left square bracket
@ WKC_SEMICOLON
; Semicolon
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Functions/types related to loading libraries dynamically.
#define Point
Macro that prevents name conflicts between included headers.
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
constexpr T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
bool HasStringInExtensionList(std::string_view string, std::string_view substring)
Find a substring in a string made of space delimited elements.
OpenGL video driver support.
void GetKeyboardLayout()
Retrieve keyboard layout from language string or (if set) config file.
bool CopyPalette(Palette &local_palette, bool force_copy)
Copy the current palette if the palette was updated.
Functions related to modal progress.
Pseudo random number generator.
A number of safeguards to prevent using unsafe methods.
static void FindResolutions()
Find and store all possible resolutions into _resolutions.
ClientSettings _settings_client
The current settings for this game.
Definition of base types and functions in a cross-platform compatible way.
char32_t Utf16DecodeSurrogate(uint lead, uint trail)
Convert an UTF-16 surrogate pair to the corresponding Unicode character.
bool Utf16IsLeadSurrogate(uint c)
Is the given character a lead surrogate code point?
bool Utf16IsTrailSurrogate(uint c)
Is the given character a lead surrogate code point?
std::vector< std::string > StringList
Type for a list of strings.
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
Colour palette[256]
Current palette. Entry 0 has to be always fully transparent!
Specification of a rectangle with absolute coordinates of all edges.
Functions related to text effects.
Handling of UTF-8 encoded data.
bool _video_vsync
Whether we should use vsync (only if active video driver supports HW acceleration).
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.
std::wstring OTTD2FS(std::string_view name)
Convert from OpenTTD's encoding to a wide string.
std::string FS2OTTD(std::wstring_view name)
Convert to OpenTTD's encoding from a wide string.
Declarations of functions for MS windows systems.
static LRESULT HandleCharMsg(uint keycode, char32_t charcode)
Forward key presses to the window system.
static bool DrawIMECompositionString()
Should we draw the composition string ourself, i.e is this a normal IME?
static LRESULT HandleIMEComposition(HWND hwnd, WPARAM wParam, LPARAM lParam)
Handle WM_IME_COMPOSITION messages.
static void SetCandidatePos(HWND hwnd)
Set the position of the candidate window.
static void CancelIMEComposition(HWND hwnd)
Clear the current composition string.
static void SetCompositionPos(HWND hwnd)
Set position of the composition window to the caret position.
Base of the Windows video driver.
Window * _focused_window
Window that currently has focus.
void ReInitAllWindows(bool zoom_changed)
Re-initialize all windows.
bool EditBoxInGlobalFocus()
Check if an edit box is in global focus.
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...
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.