gl_manager_windows_native.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. /**************************************************************************/
  2. /* gl_manager_windows_native.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "gl_manager_windows_native.h"
  31. #if defined(WINDOWS_ENABLED) && defined(GLES3_ENABLED)
  32. #include "core/config/project_settings.h"
  33. #include "core/version.h"
  34. #include "thirdparty/nvapi/nvapi_minimal.h"
  35. #include <dwmapi.h>
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
  39. #define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
  40. #define WGL_CONTEXT_FLAGS_ARB 0x2094
  41. #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
  42. #define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
  43. #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
  44. #define _WGL_CONTEXT_DEBUG_BIT_ARB 0x0001
  45. #if defined(__GNUC__)
  46. // Workaround GCC warning from -Wcast-function-type.
  47. #define GetProcAddress (void *)GetProcAddress
  48. #endif
  49. typedef HGLRC(APIENTRY *PFNWGLCREATECONTEXT)(HDC);
  50. typedef BOOL(APIENTRY *PFNWGLDELETECONTEXT)(HGLRC);
  51. typedef BOOL(APIENTRY *PFNWGLMAKECURRENT)(HDC, HGLRC);
  52. typedef HGLRC(APIENTRY *PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int *);
  53. typedef void *(APIENTRY *PFNWGLGETPROCADDRESS)(LPCSTR);
  54. static String format_error_message(DWORD id) {
  55. LPWSTR messageBuffer = nullptr;
  56. size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  57. nullptr, id, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, nullptr);
  58. String msg = "Error " + itos(id) + ": " + String::utf16((const char16_t *)messageBuffer, size);
  59. LocalFree(messageBuffer);
  60. return msg;
  61. }
  62. const int OGL_THREAD_CONTROL_ID = 0x20C1221E;
  63. const int OGL_THREAD_CONTROL_DISABLE = 0x00000002;
  64. const int OGL_THREAD_CONTROL_ENABLE = 0x00000001;
  65. const int VRR_MODE_ID = 0x1194F158;
  66. const int VRR_MODE_FULLSCREEN_ONLY = 0x1;
  67. typedef int(__cdecl *NvAPI_Initialize_t)();
  68. typedef int(__cdecl *NvAPI_Unload_t)();
  69. typedef int(__cdecl *NvAPI_GetErrorMessage_t)(unsigned int, NvAPI_ShortString);
  70. typedef int(__cdecl *NvAPI_DRS_CreateSession_t)(NvDRSSessionHandle *);
  71. typedef int(__cdecl *NvAPI_DRS_DestroySession_t)(NvDRSSessionHandle);
  72. typedef int(__cdecl *NvAPI_DRS_LoadSettings_t)(NvDRSSessionHandle);
  73. typedef int(__cdecl *NvAPI_DRS_CreateProfile_t)(NvDRSSessionHandle, NVDRS_PROFILE *, NvDRSProfileHandle *);
  74. typedef int(__cdecl *NvAPI_DRS_CreateApplication_t)(NvDRSSessionHandle, NvDRSProfileHandle, NVDRS_APPLICATION *);
  75. typedef int(__cdecl *NvAPI_DRS_SaveSettings_t)(NvDRSSessionHandle);
  76. typedef int(__cdecl *NvAPI_DRS_SetSetting_t)(NvDRSSessionHandle, NvDRSProfileHandle, NVDRS_SETTING *);
  77. typedef int(__cdecl *NvAPI_DRS_FindProfileByName_t)(NvDRSSessionHandle, NvAPI_UnicodeString, NvDRSProfileHandle *);
  78. typedef int(__cdecl *NvAPI_DRS_GetApplicationInfo_t)(NvDRSSessionHandle, NvDRSProfileHandle, NvAPI_UnicodeString, NVDRS_APPLICATION *);
  79. typedef int(__cdecl *NvAPI_DRS_DeleteProfile_t)(NvDRSSessionHandle, NvDRSProfileHandle);
  80. NvAPI_GetErrorMessage_t NvAPI_GetErrorMessage__;
  81. static bool nvapi_err_check(const char *msg, int status) {
  82. if (status != 0) {
  83. if (OS::get_singleton()->is_stdout_verbose()) {
  84. NvAPI_ShortString err_desc = { 0 };
  85. NvAPI_GetErrorMessage__(status, err_desc);
  86. print_verbose(vformat("%s: %s(code %d)", msg, err_desc, status));
  87. }
  88. return false;
  89. }
  90. return true;
  91. }
  92. // On windows we have to customize the NVIDIA application profile:
  93. // * disable threaded optimization when using NVIDIA cards to avoid stuttering, see
  94. // https://stackoverflow.com/questions/36959508/nvidia-graphics-driver-causing-noticeable-frame-stuttering/37632948
  95. // https://github.com/Ryujinx/Ryujinx/blob/master/src/Ryujinx.Common/GraphicsDriver/NVThreadedOptimization.cs
  96. // * disable G-SYNC in windowed mode, as it results in unstable editor refresh rates
  97. void GLManagerNative_Windows::_nvapi_setup_profile() {
  98. HMODULE nvapi = nullptr;
  99. #ifdef _WIN64
  100. nvapi = LoadLibraryA("nvapi64.dll");
  101. #else
  102. nvapi = LoadLibraryA("nvapi.dll");
  103. #endif
  104. if (nvapi == nullptr) {
  105. return;
  106. }
  107. void *(__cdecl * NvAPI_QueryInterface)(unsigned int interface_id) = nullptr;
  108. NvAPI_QueryInterface = (void *(__cdecl *)(unsigned int))(void *)GetProcAddress(nvapi, "nvapi_QueryInterface");
  109. if (NvAPI_QueryInterface == nullptr) {
  110. print_verbose("Error getting NVAPI NvAPI_QueryInterface");
  111. return;
  112. }
  113. // Setup NVAPI function pointers
  114. NvAPI_Initialize_t NvAPI_Initialize = (NvAPI_Initialize_t)NvAPI_QueryInterface(0x0150E828);
  115. NvAPI_GetErrorMessage__ = (NvAPI_GetErrorMessage_t)NvAPI_QueryInterface(0x6C2D048C);
  116. NvAPI_DRS_CreateSession_t NvAPI_DRS_CreateSession = (NvAPI_DRS_CreateSession_t)NvAPI_QueryInterface(0x0694D52E);
  117. NvAPI_DRS_DestroySession_t NvAPI_DRS_DestroySession = (NvAPI_DRS_DestroySession_t)NvAPI_QueryInterface(0xDAD9CFF8);
  118. NvAPI_Unload_t NvAPI_Unload = (NvAPI_Unload_t)NvAPI_QueryInterface(0xD22BDD7E);
  119. NvAPI_DRS_LoadSettings_t NvAPI_DRS_LoadSettings = (NvAPI_DRS_LoadSettings_t)NvAPI_QueryInterface(0x375DBD6B);
  120. NvAPI_DRS_CreateProfile_t NvAPI_DRS_CreateProfile = (NvAPI_DRS_CreateProfile_t)NvAPI_QueryInterface(0xCC176068);
  121. NvAPI_DRS_CreateApplication_t NvAPI_DRS_CreateApplication = (NvAPI_DRS_CreateApplication_t)NvAPI_QueryInterface(0x4347A9DE);
  122. NvAPI_DRS_SaveSettings_t NvAPI_DRS_SaveSettings = (NvAPI_DRS_SaveSettings_t)NvAPI_QueryInterface(0xFCBC7E14);
  123. NvAPI_DRS_SetSetting_t NvAPI_DRS_SetSetting = (NvAPI_DRS_SetSetting_t)NvAPI_QueryInterface(0x577DD202);
  124. NvAPI_DRS_FindProfileByName_t NvAPI_DRS_FindProfileByName = (NvAPI_DRS_FindProfileByName_t)NvAPI_QueryInterface(0x7E4A9A0B);
  125. NvAPI_DRS_GetApplicationInfo_t NvAPI_DRS_GetApplicationInfo = (NvAPI_DRS_GetApplicationInfo_t)NvAPI_QueryInterface(0xED1F8C69);
  126. NvAPI_DRS_DeleteProfile_t NvAPI_DRS_DeleteProfile = (NvAPI_DRS_DeleteProfile_t)NvAPI_QueryInterface(0x17093206);
  127. if (!nvapi_err_check("NVAPI: Init failed", NvAPI_Initialize())) {
  128. return;
  129. }
  130. print_verbose("NVAPI: Init OK!");
  131. NvDRSSessionHandle session_handle;
  132. if (NvAPI_DRS_CreateSession == nullptr) {
  133. return;
  134. }
  135. if (!nvapi_err_check("NVAPI: Error creating DRS session", NvAPI_DRS_CreateSession(&session_handle))) {
  136. NvAPI_Unload();
  137. return;
  138. }
  139. if (!nvapi_err_check("NVAPI: Error loading DRS settings", NvAPI_DRS_LoadSettings(session_handle))) {
  140. NvAPI_DRS_DestroySession(session_handle);
  141. NvAPI_Unload();
  142. return;
  143. }
  144. String app_executable_name = OS::get_singleton()->get_executable_path().get_file();
  145. String app_profile_name = GLOBAL_GET("application/config/name");
  146. // We need a name anyways, so let's use the engine name if an application name is not available
  147. // (this is used mostly by the Project Manager)
  148. if (app_profile_name.is_empty()) {
  149. app_profile_name = VERSION_NAME;
  150. }
  151. String old_profile_name = app_profile_name + " Nvidia Profile";
  152. Char16String app_profile_name_u16 = app_profile_name.utf16();
  153. Char16String old_profile_name_u16 = old_profile_name.utf16();
  154. Char16String app_executable_name_u16 = app_executable_name.utf16();
  155. // A previous error in app creation logic could result in invalid profiles,
  156. // clean these if they exist before proceeding.
  157. NvDRSProfileHandle old_profile_handle;
  158. int old_status = NvAPI_DRS_FindProfileByName(session_handle, (NvU16 *)(old_profile_name_u16.ptrw()), &old_profile_handle);
  159. if (old_status == 0) {
  160. print_verbose("NVAPI: Deleting old profile...");
  161. if (!nvapi_err_check("NVAPI: Error deleting old profile", NvAPI_DRS_DeleteProfile(session_handle, old_profile_handle))) {
  162. NvAPI_DRS_DestroySession(session_handle);
  163. NvAPI_Unload();
  164. return;
  165. }
  166. if (!nvapi_err_check("NVAPI: Error deleting old profile", NvAPI_DRS_SaveSettings(session_handle))) {
  167. NvAPI_DRS_DestroySession(session_handle);
  168. NvAPI_Unload();
  169. return;
  170. }
  171. }
  172. NvDRSProfileHandle profile_handle = nullptr;
  173. int profile_status = NvAPI_DRS_FindProfileByName(session_handle, (NvU16 *)(app_profile_name_u16.ptrw()), &profile_handle);
  174. if (profile_status != 0) {
  175. print_verbose("NVAPI: Profile not found, creating...");
  176. NVDRS_PROFILE profile_info;
  177. profile_info.version = NVDRS_PROFILE_VER;
  178. profile_info.isPredefined = 0;
  179. memcpy(profile_info.profileName, app_profile_name_u16.get_data(), sizeof(char16_t) * app_profile_name_u16.size());
  180. if (!nvapi_err_check("NVAPI: Error creating profile", NvAPI_DRS_CreateProfile(session_handle, &profile_info, &profile_handle))) {
  181. NvAPI_DRS_DestroySession(session_handle);
  182. NvAPI_Unload();
  183. return;
  184. }
  185. }
  186. NVDRS_APPLICATION_V4 app;
  187. app.version = NVDRS_APPLICATION_VER_V4;
  188. int app_status = NvAPI_DRS_GetApplicationInfo(session_handle, profile_handle, (NvU16 *)(app_executable_name_u16.ptrw()), &app);
  189. if (app_status != 0) {
  190. print_verbose("NVAPI: Application not found in profile, creating...");
  191. app.isPredefined = 0;
  192. memcpy(app.appName, app_executable_name_u16.get_data(), sizeof(char16_t) * app_executable_name_u16.size());
  193. memcpy(app.launcher, L"", sizeof(wchar_t));
  194. memcpy(app.fileInFolder, L"", sizeof(wchar_t));
  195. if (!nvapi_err_check("NVAPI: Error creating application", NvAPI_DRS_CreateApplication(session_handle, profile_handle, &app))) {
  196. NvAPI_DRS_DestroySession(session_handle);
  197. NvAPI_Unload();
  198. return;
  199. }
  200. }
  201. NVDRS_SETTING ogl_thread_control_setting = {};
  202. ogl_thread_control_setting.version = NVDRS_SETTING_VER;
  203. ogl_thread_control_setting.settingId = OGL_THREAD_CONTROL_ID;
  204. ogl_thread_control_setting.settingType = NVDRS_DWORD_TYPE;
  205. int thread_control_val = OGL_THREAD_CONTROL_DISABLE;
  206. if (!GLOBAL_GET("rendering/gl_compatibility/nvidia_disable_threaded_optimization")) {
  207. thread_control_val = OGL_THREAD_CONTROL_ENABLE;
  208. }
  209. ogl_thread_control_setting.u32CurrentValue = thread_control_val;
  210. if (!nvapi_err_check("NVAPI: Error calling NvAPI_DRS_SetSetting", NvAPI_DRS_SetSetting(session_handle, profile_handle, &ogl_thread_control_setting))) {
  211. NvAPI_DRS_DestroySession(session_handle);
  212. NvAPI_Unload();
  213. return;
  214. }
  215. NVDRS_SETTING vrr_mode_setting = {};
  216. vrr_mode_setting.version = NVDRS_SETTING_VER;
  217. vrr_mode_setting.settingId = VRR_MODE_ID;
  218. vrr_mode_setting.settingType = NVDRS_DWORD_TYPE;
  219. vrr_mode_setting.u32CurrentValue = VRR_MODE_FULLSCREEN_ONLY;
  220. if (!nvapi_err_check("NVAPI: Error calling NvAPI_DRS_SetSetting", NvAPI_DRS_SetSetting(session_handle, profile_handle, &vrr_mode_setting))) {
  221. NvAPI_DRS_DestroySession(session_handle);
  222. NvAPI_Unload();
  223. return;
  224. }
  225. if (!nvapi_err_check("NVAPI: Error saving settings", NvAPI_DRS_SaveSettings(session_handle))) {
  226. NvAPI_DRS_DestroySession(session_handle);
  227. NvAPI_Unload();
  228. return;
  229. }
  230. if (thread_control_val == OGL_THREAD_CONTROL_DISABLE) {
  231. print_verbose("NVAPI: Disabled OpenGL threaded optimization successfully");
  232. } else {
  233. print_verbose("NVAPI: Enabled OpenGL threaded optimization successfully");
  234. }
  235. print_verbose("NVAPI: Disabled G-SYNC for windowed mode successfully");
  236. NvAPI_DRS_DestroySession(session_handle);
  237. }
  238. int GLManagerNative_Windows::_find_or_create_display(GLWindow &win) {
  239. // find display NYI, only 1 supported so far
  240. if (_displays.size()) {
  241. return 0;
  242. }
  243. // create
  244. GLDisplay d_temp = {};
  245. _displays.push_back(d_temp);
  246. int new_display_id = _displays.size() - 1;
  247. // create context
  248. GLDisplay &d = _displays[new_display_id];
  249. Error err = _create_context(win, d);
  250. if (err != OK) {
  251. // not good
  252. // delete the _display?
  253. _displays.remove_at(new_display_id);
  254. return -1;
  255. }
  256. return new_display_id;
  257. }
  258. static Error _configure_pixel_format(HDC hDC) {
  259. static PIXELFORMATDESCRIPTOR pfd = {
  260. sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
  261. 1,
  262. PFD_DRAW_TO_WINDOW | // Format Must Support Window
  263. PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
  264. PFD_DOUBLEBUFFER,
  265. (BYTE)PFD_TYPE_RGBA,
  266. (BYTE)(OS::get_singleton()->is_layered_allowed() ? 32 : 24),
  267. (BYTE)0, (BYTE)0, (BYTE)0, (BYTE)0, (BYTE)0, (BYTE)0, // Color Bits Ignored
  268. (BYTE)(OS::get_singleton()->is_layered_allowed() ? 8 : 0), // Alpha Buffer
  269. (BYTE)0, // Shift Bit Ignored
  270. (BYTE)0, // No Accumulation Buffer
  271. (BYTE)0, (BYTE)0, (BYTE)0, (BYTE)0, // Accumulation Bits Ignored
  272. (BYTE)24, // 24Bit Z-Buffer (Depth Buffer)
  273. (BYTE)0, // No Stencil Buffer
  274. (BYTE)0, // No Auxiliary Buffer
  275. (BYTE)PFD_MAIN_PLANE, // Main Drawing Layer
  276. (BYTE)0, // Reserved
  277. 0, 0, 0 // Layer Masks Ignored
  278. };
  279. int pixel_format = ChoosePixelFormat(hDC, &pfd);
  280. if (!pixel_format) // Did Windows Find A Matching Pixel Format?
  281. {
  282. return ERR_CANT_CREATE; // Return FALSE
  283. }
  284. BOOL ret = SetPixelFormat(hDC, pixel_format, &pfd);
  285. if (!ret) // Are We Able To Set The Pixel Format?
  286. {
  287. return ERR_CANT_CREATE; // Return FALSE
  288. }
  289. return OK;
  290. }
  291. PFNWGLCREATECONTEXT gd_wglCreateContext;
  292. PFNWGLMAKECURRENT gd_wglMakeCurrent;
  293. PFNWGLDELETECONTEXT gd_wglDeleteContext;
  294. PFNWGLGETPROCADDRESS gd_wglGetProcAddress;
  295. Error GLManagerNative_Windows::_create_context(GLWindow &win, GLDisplay &gl_display) {
  296. Error err = _configure_pixel_format(win.hDC);
  297. if (err != OK) {
  298. return err;
  299. }
  300. HMODULE module = LoadLibraryW(L"opengl32.dll");
  301. if (!module) {
  302. return ERR_CANT_CREATE;
  303. }
  304. gd_wglCreateContext = (PFNWGLCREATECONTEXT)GetProcAddress(module, "wglCreateContext");
  305. gd_wglMakeCurrent = (PFNWGLMAKECURRENT)GetProcAddress(module, "wglMakeCurrent");
  306. gd_wglDeleteContext = (PFNWGLDELETECONTEXT)GetProcAddress(module, "wglDeleteContext");
  307. gd_wglGetProcAddress = (PFNWGLGETPROCADDRESS)GetProcAddress(module, "wglGetProcAddress");
  308. if (!gd_wglCreateContext || !gd_wglMakeCurrent || !gd_wglDeleteContext || !gd_wglGetProcAddress) {
  309. return ERR_CANT_CREATE;
  310. }
  311. gl_display.hRC = gd_wglCreateContext(win.hDC);
  312. if (!gl_display.hRC) // Are We Able To Get A Rendering Context?
  313. {
  314. return ERR_CANT_CREATE; // Return FALSE
  315. }
  316. if (!gd_wglMakeCurrent(win.hDC, gl_display.hRC)) {
  317. ERR_PRINT("Could not attach OpenGL context to newly created window: " + format_error_message(GetLastError()));
  318. }
  319. int attribs[] = {
  320. WGL_CONTEXT_MAJOR_VERSION_ARB, 3, //we want a 3.3 context
  321. WGL_CONTEXT_MINOR_VERSION_ARB, 3,
  322. //and it shall be forward compatible so that we can only use up to date functionality
  323. WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
  324. WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB /*| _WGL_CONTEXT_DEBUG_BIT_ARB*/,
  325. 0
  326. }; //zero indicates the end of the array
  327. PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = nullptr; //pointer to the method
  328. wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)gd_wglGetProcAddress("wglCreateContextAttribsARB");
  329. if (wglCreateContextAttribsARB == nullptr) //OpenGL 3.0 is not supported
  330. {
  331. gd_wglDeleteContext(gl_display.hRC);
  332. gl_display.hRC = nullptr;
  333. return ERR_CANT_CREATE;
  334. }
  335. HGLRC new_hRC = wglCreateContextAttribsARB(win.hDC, nullptr, attribs);
  336. if (!new_hRC) {
  337. gd_wglDeleteContext(gl_display.hRC);
  338. gl_display.hRC = nullptr;
  339. return ERR_CANT_CREATE;
  340. }
  341. if (!gd_wglMakeCurrent(win.hDC, nullptr)) {
  342. ERR_PRINT("Could not detach OpenGL context from newly created window: " + format_error_message(GetLastError()));
  343. }
  344. gd_wglDeleteContext(gl_display.hRC);
  345. gl_display.hRC = new_hRC;
  346. if (!gd_wglMakeCurrent(win.hDC, gl_display.hRC)) // Try to activate the rendering context.
  347. {
  348. ERR_PRINT("Could not attach OpenGL context to newly created window with replaced OpenGL context: " + format_error_message(GetLastError()));
  349. gd_wglDeleteContext(gl_display.hRC);
  350. gl_display.hRC = nullptr;
  351. return ERR_CANT_CREATE;
  352. }
  353. if (!wglSwapIntervalEXT) {
  354. wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)gd_wglGetProcAddress("wglSwapIntervalEXT");
  355. }
  356. return OK;
  357. }
  358. Error GLManagerNative_Windows::window_create(DisplayServer::WindowID p_window_id, HWND p_hwnd, HINSTANCE p_hinstance, int p_width, int p_height) {
  359. HDC hDC = GetDC(p_hwnd);
  360. if (!hDC) {
  361. return ERR_CANT_CREATE;
  362. }
  363. // configure the HDC to use a compatible pixel format
  364. Error result = _configure_pixel_format(hDC);
  365. if (result != OK) {
  366. return result;
  367. }
  368. GLWindow win;
  369. win.hwnd = p_hwnd;
  370. win.hDC = hDC;
  371. win.gldisplay_id = _find_or_create_display(win);
  372. if (win.gldisplay_id == -1) {
  373. return FAILED;
  374. }
  375. // WARNING: `p_window_id` is an eternally growing integer since popup windows keep coming and going
  376. // and each of them has a higher id than the previous, so it must be used in a map not a vector.
  377. _windows[p_window_id] = win;
  378. // make current
  379. window_make_current(p_window_id);
  380. return OK;
  381. }
  382. void GLManagerNative_Windows::window_destroy(DisplayServer::WindowID p_window_id) {
  383. GLWindow &win = get_window(p_window_id);
  384. if (_current_window == &win) {
  385. _current_window = nullptr;
  386. }
  387. _windows.erase(p_window_id);
  388. }
  389. void GLManagerNative_Windows::release_current() {
  390. if (!_current_window) {
  391. return;
  392. }
  393. if (!gd_wglMakeCurrent(_current_window->hDC, nullptr)) {
  394. ERR_PRINT("Could not detach OpenGL context from window marked current: " + format_error_message(GetLastError()));
  395. }
  396. _current_window = nullptr;
  397. }
  398. void GLManagerNative_Windows::window_make_current(DisplayServer::WindowID p_window_id) {
  399. if (p_window_id == -1) {
  400. return;
  401. }
  402. // crash if our data structures are out of sync, i.e. not found
  403. GLWindow &win = _windows[p_window_id];
  404. // noop
  405. if (&win == _current_window) {
  406. return;
  407. }
  408. const GLDisplay &disp = get_display(win.gldisplay_id);
  409. if (!gd_wglMakeCurrent(win.hDC, disp.hRC)) {
  410. ERR_PRINT("Could not switch OpenGL context to other window: " + format_error_message(GetLastError()));
  411. }
  412. _current_window = &win;
  413. }
  414. void GLManagerNative_Windows::swap_buffers() {
  415. SwapBuffers(_current_window->hDC);
  416. }
  417. Error GLManagerNative_Windows::initialize() {
  418. _nvapi_setup_profile();
  419. return OK;
  420. }
  421. void GLManagerNative_Windows::set_use_vsync(DisplayServer::WindowID p_window_id, bool p_use) {
  422. GLWindow &win = get_window(p_window_id);
  423. if (&win != _current_window) {
  424. window_make_current(p_window_id);
  425. }
  426. if (wglSwapIntervalEXT) {
  427. win.use_vsync = p_use;
  428. if (!wglSwapIntervalEXT(p_use ? 1 : 0)) {
  429. WARN_PRINT_ONCE("Could not set V-Sync mode, as changing V-Sync mode is not supported by the graphics driver.");
  430. }
  431. } else {
  432. WARN_PRINT_ONCE("Could not set V-Sync mode, as changing V-Sync mode is not supported by the graphics driver.");
  433. }
  434. }
  435. bool GLManagerNative_Windows::is_using_vsync(DisplayServer::WindowID p_window_id) const {
  436. return get_window(p_window_id).use_vsync;
  437. }
  438. HDC GLManagerNative_Windows::get_hdc(DisplayServer::WindowID p_window_id) {
  439. return get_window(p_window_id).hDC;
  440. }
  441. HGLRC GLManagerNative_Windows::get_hglrc(DisplayServer::WindowID p_window_id) {
  442. const GLWindow &win = get_window(p_window_id);
  443. const GLDisplay &disp = get_display(win.gldisplay_id);
  444. return disp.hRC;
  445. }
  446. GLManagerNative_Windows::GLManagerNative_Windows() {
  447. direct_render = false;
  448. glx_minor = glx_major = 0;
  449. _current_window = nullptr;
  450. }
  451. GLManagerNative_Windows::~GLManagerNative_Windows() {
  452. release_current();
  453. }
  454. #endif // WINDOWS_ENABLED && GLES3_ENABLED