From b46525072b7829aa326ae463f8b8a7d0edc87f95 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Tue, 3 Nov 2026 09:39:42 +0530 Subject: [PATCH] Move OpenGL context creation from glfw into the GPU driver glfw is now a windowing only library. It no longer creates OpenGL contexts and contains no GLX, EGL, NSGL or OSMesa code. Instead it exposes native window handles, and the GPU driver creates surfaces that render into them, owning everything needed to render and present, such as OpenGL contexts or, in future, Vulkan swapchains. The GPU driver API (now version 2) gains surfaces: creation from native X11, Wayland and Cocoa windows, making current, resizing, presenting, swap interval, handling native view changes and recreation (macOS) and choosing the X11 visual before window creation. The OpenGL driver implements them with GLX on X11, EGL on Wayland and NSGL on macOS, all ported from glfw, loading every library at runtime. glfw gains a GLFW_X11_VISUAL_ID window hint, a native surface changed callback (used on macOS where the NSOpenGLContext must be updated) and glfwWindowContentsPresented(), which on Wayland commits surface state after a frame is presented. The OpenGL context API, hints and the share parameter of glfwCreateWindow() are removed. The macOS (NSGL) code is untested as it could not be built. --- glfw/cocoa_init.m | 7 +- glfw/cocoa_platform.h | 1 - glfw/cocoa_window.m | 80 +---- glfw/context.c | 453 --------------------------- glfw/egl_context.c | 642 -------------------------------------- glfw/egl_context.h | 228 -------------- glfw/glfw.py | 7 +- glfw/glfw3.h | 575 +++------------------------------- glfw/glx_context.c | 549 -------------------------------- glfw/glx_context.h | 176 ----------- glfw/init.c | 7 +- glfw/internal.h | 144 +-------- glfw/nsgl_context.h | 51 --- glfw/nsgl_context.m | 333 -------------------- glfw/osmesa_context.c | 294 ----------------- glfw/osmesa_context.h | 85 ----- glfw/source-info.json | 21 +- glfw/vulkan.c | 5 - glfw/window.c | 107 ++----- glfw/wl_init.c | 33 +- glfw/wl_platform.h | 15 - glfw/wl_window.c | 58 +--- glfw/x11_init.c | 7 +- glfw/x11_platform.h | 1 - glfw/x11_window.c | 96 ++---- gpu/api.h | 101 +++++- gpu/opengl/driver.c | 217 ++++++++++++- gpu/opengl/egl.c | 470 ++++++++++++++++++++++++++++ gpu/opengl/glx.c | 501 +++++++++++++++++++++++++++++ gpu/opengl/nsgl.m | 251 +++++++++++++++ gpu/opengl/platform.h | 63 ++++ kitty/fast_data_types.pyi | 32 -- kitty/glfw-wrapper.c | 43 ++- kitty/glfw-wrapper.h | 286 +++-------------- kitty/glfw.c | 195 +++++++----- kitty/gpu.c | 15 +- kitty/gpu.h | 60 +++- kitty/state.h | 3 +- setup.py | 25 +- 39 files changed, 2005 insertions(+), 4232 deletions(-) delete mode 100644 glfw/context.c delete mode 100644 glfw/egl_context.c delete mode 100644 glfw/egl_context.h delete mode 100644 glfw/glx_context.c delete mode 100644 glfw/glx_context.h delete mode 100644 glfw/nsgl_context.h delete mode 100644 glfw/nsgl_context.m delete mode 100644 glfw/osmesa_context.c delete mode 100644 glfw/osmesa_context.h create mode 100644 gpu/opengl/egl.c create mode 100644 gpu/opengl/glx.c create mode 100644 gpu/opengl/nsgl.m create mode 100644 gpu/opengl/platform.h diff --git a/glfw/cocoa_init.m b/glfw/cocoa_init.m index eb3680225..0561e4f34 100644 --- a/glfw/cocoa_init.m +++ b/glfw/cocoa_init.m @@ -303,9 +303,7 @@ static GLFWapplicationshouldhandlereopenfun handle_reopen_callback = NULL; (void)notification; _GLFWwindow *window; - for (window = _glfw.windowListHead; window; window = window->next) { - if (window->context.client != GLFW_NO_API) [window->context.nsgl.object update]; - } + for (window = _glfw.windowListHead; window; window = window->next) { _glfwInputNativeSurfaceChanged(window); } _glfwPollMonitorsNS(); } @@ -1031,7 +1029,6 @@ _glfwPlatformTerminate(void) { _glfw.ns.appleSettings = nil; } - _glfwTerminateNSGL(); if (global_shortcuts != nil) { [global_shortcuts release]; global_shortcuts = nil; @@ -1042,7 +1039,7 @@ _glfwPlatformTerminate(void) { const char * _glfwPlatformGetVersionString(void) { - return _GLFW_VERSION_NUMBER " Cocoa NSGL EGL OSMesa" + return _GLFW_VERSION_NUMBER " Cocoa" #if defined(_GLFW_BUILD_DLL) " dynamic" #endif diff --git a/glfw/cocoa_platform.h b/glfw/cocoa_platform.h index 79ffae061..5f2820e6f 100644 --- a/glfw/cocoa_platform.h +++ b/glfw/cocoa_platform.h @@ -91,7 +91,6 @@ typedef VkResult(APIENTRY *PFN_vkCreateMetalSurfaceEXT)(VkInstance, const VkMeta #include "posix_thread.h" #include "cocoa_joystick.h" -#include "nsgl_context.h" #define _glfw_dlopen(name) dlopen(name, RTLD_LAZY | RTLD_LOCAL) #define _glfw_dlclose(handle) dlclose(handle) diff --git a/glfw/cocoa_window.m b/glfw/cocoa_window.m index 3242f63c1..9995e4950 100644 --- a/glfw/cocoa_window.m +++ b/glfw/cocoa_window.m @@ -679,7 +679,7 @@ static void flush_focus_loss_text(_GLFWwindow *window); } [currentScreenStates release]; - if (window->context.client != GLFW_NO_API) [window->context.nsgl.object update]; + _glfwInputNativeSurfaceChanged(window); if (_glfw.ns.disabledCursorWindow == window) _glfwCenterCursorInContentArea(window); @@ -711,7 +711,7 @@ static void flush_focus_loss_text(_GLFWwindow *window); - (void)windowDidMove:(NSNotification *)notification { (void)notification; - if (window->context.client != GLFW_NO_API) [window->context.nsgl.object update]; + _glfwInputNativeSurfaceChanged(window); if (_glfw.ns.disabledCursorWindow == window) _glfwCenterCursorInContentArea(window); @@ -1024,13 +1024,7 @@ static void flush_focus_loss_text(_GLFWwindow *window); - (void)updateLayer { if (!window) return; - if (window->context.client != GLFW_NO_API) { - @try { - [window->context.nsgl.object update]; - } @catch (NSException *e) { - _glfwInputError(GLFW_PLATFORM_ERROR, "Failed to update NSGL Context object with error: %s (%s)", [[e name] UTF8String], [[e reason] UTF8String]); - } - } + _glfwInputNativeSurfaceChanged(window); _glfwInputWindowDamage(window); } @@ -2705,8 +2699,7 @@ createNativeWindow(_GLFWwindow *window, const _GLFWwndconfig *wndconfig, const _ ////////////////////////////////////////////////////////////////////////// int -_glfwPlatformCreateWindow( - _GLFWwindow *window, const _GLFWwndconfig *wndconfig, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig, const GLFWLayerShellConfig *lsc) { +_glfwPlatformCreateWindow(_GLFWwindow *window, const _GLFWwndconfig *wndconfig, const _GLFWfbconfig *fbconfig, const GLFWLayerShellConfig *lsc) { window->ns.deadKeyState = 0; if (lsc) { window->ns.layer_shell.is_active = true; @@ -2724,24 +2717,6 @@ _glfwPlatformCreateWindow( case DEFAULT_COLORSPACE: break; } - if (ctxconfig->client != GLFW_NO_API) { - if (ctxconfig->source == GLFW_NATIVE_CONTEXT_API) { - if (!_glfwInitNSGL()) return false; - if (!_glfwCreateContextNSGL(window, ctxconfig, fbconfig)) return false; - } else if (ctxconfig->source == GLFW_EGL_CONTEXT_API) { - // EGL implementation on macOS use CALayer* EGLNativeWindowType so we - // need to get the layer for EGL window surface creation. - [window->ns.view setWantsLayer:YES]; - window->ns.layer = [window->ns.view layer]; - - if (!_glfwInitEGL()) return false; - if (!_glfwCreateContextEGL(window, ctxconfig, fbconfig)) return false; - } else if (ctxconfig->source == GLFW_OSMESA_CONTEXT_API) { - if (!_glfwInitOSMesa()) return false; - if (!_glfwCreateContextOSMesa(window, ctxconfig, fbconfig)) return false; - } - } - if (window->monitor) { // Do not show the window here until after setting the window size, maximized state, and full screen // _glfwPlatformShowWindow(window); @@ -2768,8 +2743,6 @@ _glfwPlatformDestroyWindow(_GLFWwindow *window) { if (window->monitor) releaseMonitor(window); - if (window->context.destroy) window->context.destroy(window); - [w setDelegate:nil]; [window->ns.delegate cleanup]; [window->ns.delegate release]; @@ -3978,40 +3951,8 @@ _glfwPlatformSetClipboard(GLFWClipboardType t) { } // }}} -EGLenum -_glfwPlatformGetEGLPlatform(EGLint **attribs) { - if (_glfw.egl.ANGLE_platform_angle) { - int type = 0; - - if (_glfw.egl.ANGLE_platform_angle_opengl) { - if (_glfw.hints.init.angleType == GLFW_ANGLE_PLATFORM_TYPE_OPENGL) type = EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE; - } - - if (_glfw.egl.ANGLE_platform_angle_metal) { - if (_glfw.hints.init.angleType == GLFW_ANGLE_PLATFORM_TYPE_METAL) type = EGL_PLATFORM_ANGLE_TYPE_METAL_ANGLE; - } - - if (type) { - *attribs = calloc(3, sizeof(EGLint)); - (*attribs)[0] = EGL_PLATFORM_ANGLE_TYPE_ANGLE; - (*attribs)[1] = type; - (*attribs)[2] = EGL_NONE; - return EGL_PLATFORM_ANGLE_ANGLE; - } - } - - return 0; -} - -EGLNativeDisplayType -_glfwPlatformGetEGLNativeDisplay(void) { - return EGL_DEFAULT_DISPLAY; -} - -EGLNativeWindowType -_glfwPlatformGetEGLNativeWindow(_GLFWwindow *window) { - return window->ns.layer; -} +void +_glfwPlatformWindowContentsPresented(_GLFWwindow *window UNUSED) {} void _glfwPlatformGetRequiredInstanceExtensions(char **extensions) { @@ -4120,6 +4061,15 @@ glfwGetCocoaWindow(GLFWwindow *handle) { return window->ns.object; } +GLFWAPI id +glfwGetCocoaView(GLFWwindow *handle) { + _GLFWwindow *window = (_GLFWwindow *)handle; + assert(window != NULL); + + _GLFW_REQUIRE_INIT_OR_RETURN(nil); + return window->ns.view; +} + GLFWAPI GLFWcocoatextinputfilterfun glfwSetCocoaTextInputFilter(GLFWwindow *handle, GLFWcocoatextinputfilterfun callback) { _GLFWwindow *window = (_GLFWwindow *)handle; diff --git a/glfw/context.c b/glfw/context.c deleted file mode 100644 index 055c2fcfc..000000000 --- a/glfw/context.c +++ /dev/null @@ -1,453 +0,0 @@ -//======================================================================== -// GLFW 3.4 - www.glfw.org -//------------------------------------------------------------------------ -// Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2016 Camilla Löwy -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would -// be appreciated but is not required. -// -// 2. Altered source versions must be plainly marked as such, and must not -// be misrepresented as being the original software. -// -// 3. This notice may not be removed or altered from any source -// distribution. -// -//======================================================================== -// Please use C89 style variable declarations in this file because VS 2010 -//======================================================================== - -#include "internal.h" - -#include -#include -#include -#include - - -////////////////////////////////////////////////////////////////////////// -////// GLFW internal API ////// -////////////////////////////////////////////////////////////////////////// - -// Checks whether the desired context attributes are valid -// -// This function checks things like whether the specified client API version -// exists and whether all relevant options have supported and non-conflicting -// values -// -bool -_glfwIsValidContextConfig(const _GLFWctxconfig *ctxconfig) { - if (ctxconfig->share) { - if (ctxconfig->client == GLFW_NO_API || ctxconfig->share->context.client == GLFW_NO_API) { - _glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL); - return false; - } - } - - if (ctxconfig->source != GLFW_NATIVE_CONTEXT_API && ctxconfig->source != GLFW_EGL_CONTEXT_API && ctxconfig->source != GLFW_OSMESA_CONTEXT_API) { - _glfwInputError(GLFW_INVALID_ENUM, "Invalid context creation API 0x%08X", ctxconfig->source); - return false; - } - - if (ctxconfig->client != GLFW_NO_API && ctxconfig->client != GLFW_OPENGL_API && ctxconfig->client != GLFW_OPENGL_ES_API) { - _glfwInputError(GLFW_INVALID_ENUM, "Invalid client API 0x%08X", ctxconfig->client); - return false; - } - - if (ctxconfig->client == GLFW_OPENGL_API) { - if ((ctxconfig->major < 1 || ctxconfig->minor < 0) || (ctxconfig->major == 1 && ctxconfig->minor > 5) || - (ctxconfig->major == 2 && ctxconfig->minor > 1) || (ctxconfig->major == 3 && ctxconfig->minor > 3)) { - // OpenGL 1.0 is the smallest valid version - // OpenGL 1.x series ended with version 1.5 - // OpenGL 2.x series ended with version 2.1 - // OpenGL 3.x series ended with version 3.3 - // For now, let everything else through - - _glfwInputError(GLFW_INVALID_VALUE, "Invalid OpenGL version %i.%i", ctxconfig->major, ctxconfig->minor); - return false; - } - - if (ctxconfig->profile) { - if (ctxconfig->profile != GLFW_OPENGL_CORE_PROFILE && ctxconfig->profile != GLFW_OPENGL_COMPAT_PROFILE) { - _glfwInputError(GLFW_INVALID_ENUM, "Invalid OpenGL profile 0x%08X", ctxconfig->profile); - return false; - } - - if (ctxconfig->major <= 2 || (ctxconfig->major == 3 && ctxconfig->minor < 2)) { - // Desktop OpenGL context profiles are only defined for version 3.2 - // and above - - _glfwInputError(GLFW_INVALID_VALUE, "Context profiles are only defined for OpenGL version 3.2 and above"); - return false; - } - } - - if (ctxconfig->forward && ctxconfig->major <= 2) { - // Forward-compatible contexts are only defined for OpenGL version 3.0 and above - _glfwInputError(GLFW_INVALID_VALUE, "Forward-compatibility is only defined for OpenGL version 3.0 and above"); - return false; - } - } else if (ctxconfig->client == GLFW_OPENGL_ES_API) { - if (ctxconfig->major < 1 || ctxconfig->minor < 0 || (ctxconfig->major == 1 && ctxconfig->minor > 1) || - (ctxconfig->major == 2 && ctxconfig->minor > 0)) { - // OpenGL ES 1.0 is the smallest valid version - // OpenGL ES 1.x series ended with version 1.1 - // OpenGL ES 2.x series ended with version 2.0 - // For now, let everything else through - - _glfwInputError(GLFW_INVALID_VALUE, "Invalid OpenGL ES version %i.%i", ctxconfig->major, ctxconfig->minor); - return false; - } - } - - if (ctxconfig->robustness) { - if (ctxconfig->robustness != GLFW_NO_RESET_NOTIFICATION && ctxconfig->robustness != GLFW_LOSE_CONTEXT_ON_RESET) { - _glfwInputError(GLFW_INVALID_ENUM, "Invalid context robustness mode 0x%08X", ctxconfig->robustness); - return false; - } - } - - if (ctxconfig->release) { - if (ctxconfig->release != GLFW_RELEASE_BEHAVIOR_NONE && ctxconfig->release != GLFW_RELEASE_BEHAVIOR_FLUSH) { - _glfwInputError(GLFW_INVALID_ENUM, "Invalid context release behavior 0x%08X", ctxconfig->release); - return false; - } - } - - return true; -} - -// Retrieves the attributes of the current context -// -bool -_glfwRefreshContextAttribs(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig) { - int i; - _GLFWwindow *previous; - const char *version; - const char *prefixes[] = {"OpenGL ES-CM ", "OpenGL ES-CL ", "OpenGL ES ", NULL}; - - window->context.source = ctxconfig->source; - window->context.client = GLFW_OPENGL_API; - - previous = _glfwPlatformGetTls(&_glfw.contextSlot); - glfwMakeContextCurrent((GLFWwindow *)window); - - window->context.GetIntegerv = (PFNGLGETINTEGERVPROC)window->context.getProcAddress("glGetIntegerv"); - window->context.GetString = (PFNGLGETSTRINGPROC)window->context.getProcAddress("glGetString"); - if (!window->context.GetIntegerv || !window->context.GetString) { - _glfwInputError(GLFW_PLATFORM_ERROR, "Entry point retrieval is broken"); - glfwMakeContextCurrent((GLFWwindow *)previous); - return false; - } - - version = (const char *)window->context.GetString(GL_VERSION); - if (!version) { - if (ctxconfig->client == GLFW_OPENGL_API) { - _glfwInputError(GLFW_PLATFORM_ERROR, "OpenGL version string retrieval is broken"); - } else { - _glfwInputError(GLFW_PLATFORM_ERROR, "OpenGL ES version string retrieval is broken"); - } - - glfwMakeContextCurrent((GLFWwindow *)previous); - return false; - } - - for (i = 0; prefixes[i]; i++) { - const size_t length = strlen(prefixes[i]); - - if (strncmp(version, prefixes[i], length) == 0) { - version += length; - window->context.client = GLFW_OPENGL_ES_API; - break; - } - } - - if (sscanf(version, "%d.%d.%d", &window->context.major, &window->context.minor, &window->context.revision) < 1) { - if (window->context.client == GLFW_OPENGL_API) { - _glfwInputError(GLFW_PLATFORM_ERROR, "No version found in OpenGL version string"); - } else { - _glfwInputError(GLFW_PLATFORM_ERROR, "No version found in OpenGL ES version string"); - } - - glfwMakeContextCurrent((GLFWwindow *)previous); - return false; - } - - if (window->context.major < ctxconfig->major || (window->context.major == ctxconfig->major && window->context.minor < ctxconfig->minor)) { - // The desired OpenGL version is greater than the actual version - // This only happens if the machine lacks {GLX|WGL}_ARB_create_context - // /and/ the user has requested an OpenGL version greater than 1.0 - - // For API consistency, we emulate the behavior of the - // {GLX|WGL}_ARB_create_context extension and fail here - - if (window->context.client == GLFW_OPENGL_API) { - _glfwInputError( - GLFW_VERSION_UNAVAILABLE, - "Requested OpenGL version %i.%i, got version %i.%i", - ctxconfig->major, - ctxconfig->minor, - window->context.major, - window->context.minor); - } else { - _glfwInputError( - GLFW_VERSION_UNAVAILABLE, - "Requested OpenGL ES version %i.%i, got version %i.%i", - ctxconfig->major, - ctxconfig->minor, - window->context.major, - window->context.minor); - } - - glfwMakeContextCurrent((GLFWwindow *)previous); - return false; - } - - if (window->context.major >= 3) { - // OpenGL 3.0+ uses a different function for extension string retrieval - // We cache it here instead of in glfwExtensionSupported mostly to alert - // users as early as possible that their build may be broken - - window->context.GetStringi = (PFNGLGETSTRINGIPROC)window->context.getProcAddress("glGetStringi"); - if (!window->context.GetStringi) { - _glfwInputError(GLFW_PLATFORM_ERROR, "Entry point retrieval is broken"); - glfwMakeContextCurrent((GLFWwindow *)previous); - return false; - } - } - - if (window->context.client == GLFW_OPENGL_API) { - // Read back context flags (OpenGL 3.0 and above) - if (window->context.major >= 3) { - GLint flags; - window->context.GetIntegerv(GL_CONTEXT_FLAGS, &flags); - - if (flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT) window->context.forward = true; - - if (flags & GL_CONTEXT_FLAG_DEBUG_BIT) window->context.debug = true; - else if (glfwExtensionSupported("GL_ARB_debug_output") && ctxconfig->debug) { - // HACK: This is a workaround for older drivers (pre KHR_debug) - // not setting the debug bit in the context flags for - // debug contexts - window->context.debug = true; - } - - if (flags & GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR) window->context.noerror = true; - } - - // Read back OpenGL context profile (OpenGL 3.2 and above) - if (window->context.major >= 4 || (window->context.major == 3 && window->context.minor >= 2)) { - GLint mask; - window->context.GetIntegerv(GL_CONTEXT_PROFILE_MASK, &mask); - - if (mask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) window->context.profile = GLFW_OPENGL_COMPAT_PROFILE; - else if (mask & GL_CONTEXT_CORE_PROFILE_BIT) window->context.profile = GLFW_OPENGL_CORE_PROFILE; - else if (glfwExtensionSupported("GL_ARB_compatibility")) { - // HACK: This is a workaround for the compatibility profile bit - // not being set in the context flags if an OpenGL 3.2+ - // context was created without having requested a specific - // version - window->context.profile = GLFW_OPENGL_COMPAT_PROFILE; - } - } - - // Read back robustness strategy - if (glfwExtensionSupported("GL_ARB_robustness")) { - // NOTE: We avoid using the context flags for detection, as they are - // only present from 3.0 while the extension applies from 1.1 - - GLint strategy; - window->context.GetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy); - - if (strategy == GL_LOSE_CONTEXT_ON_RESET_ARB) window->context.robustness = GLFW_LOSE_CONTEXT_ON_RESET; - else if (strategy == GL_NO_RESET_NOTIFICATION_ARB) window->context.robustness = GLFW_NO_RESET_NOTIFICATION; - } - } else { - // Read back robustness strategy - if (glfwExtensionSupported("GL_EXT_robustness")) { - // NOTE: The values of these constants match those of the OpenGL ARB - // one, so we can reuse them here - - GLint strategy; - window->context.GetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, &strategy); - - if (strategy == GL_LOSE_CONTEXT_ON_RESET_ARB) window->context.robustness = GLFW_LOSE_CONTEXT_ON_RESET; - else if (strategy == GL_NO_RESET_NOTIFICATION_ARB) window->context.robustness = GLFW_NO_RESET_NOTIFICATION; - } - } - - if (glfwExtensionSupported("GL_KHR_context_flush_control")) { - GLint behavior; - window->context.GetIntegerv(GL_CONTEXT_RELEASE_BEHAVIOR, &behavior); - - if (behavior == GL_NONE) window->context.release = GLFW_RELEASE_BEHAVIOR_NONE; - else if (behavior == GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH) window->context.release = GLFW_RELEASE_BEHAVIOR_FLUSH; - } - - glfwMakeContextCurrent((GLFWwindow *)previous); - return true; -} - -// Searches an extension string for the specified extension -// -bool -_glfwStringInExtensionString(const char *string, const char *extensions) { - const char *start = extensions; - - for (;;) { - const char *where; - const char *terminator; - - where = strstr(start, string); - if (!where) return false; - - terminator = where + strlen(string); - if (where == start || *(where - 1) == ' ') { - if (*terminator == ' ' || *terminator == '\0') break; - } - - start = terminator; - } - - return true; -} - - -////////////////////////////////////////////////////////////////////////// -////// GLFW public API ////// -////////////////////////////////////////////////////////////////////////// - -GLFWAPI void -glfwMakeContextCurrent(GLFWwindow *handle) { - _GLFW_REQUIRE_INIT(); - - _GLFWwindow *window = (_GLFWwindow *)handle; - _GLFWwindow *previous = _glfwPlatformGetTls(&_glfw.contextSlot); - - if (window && window->context.client == GLFW_NO_API) { - _glfwInputError(GLFW_NO_WINDOW_CONTEXT, "Cannot make current with a window that has no OpenGL or OpenGL ES context"); - return; - } - - if (previous) { - if (!window || window->context.source != previous->context.source) previous->context.makeCurrent(NULL); - } - - if (window) window->context.makeCurrent(window); -} - -GLFWAPI GLFWwindow * -glfwGetCurrentContext(void) { - _GLFW_REQUIRE_INIT_OR_RETURN(NULL); - return _glfwPlatformGetTls(&_glfw.contextSlot); -} - -GLFWAPI void -glfwSwapBuffers(GLFWwindow *handle) { - _GLFWwindow *window = (_GLFWwindow *)handle; - assert(window != NULL); - - _GLFW_REQUIRE_INIT(); - - if (window->context.client == GLFW_NO_API) { - _glfwInputError(GLFW_NO_WINDOW_CONTEXT, "Cannot swap buffers of a window that has no OpenGL or OpenGL ES context"); - return; - } - - window->context.swapBuffers(window); -#ifdef _GLFW_WAYLAND - _glfwWaylandAfterBufferSwap(window); -#endif -} - -GLFWAPI void -glfwSwapInterval(int interval) { - _GLFWwindow *window; - - _GLFW_REQUIRE_INIT(); - - window = _glfwPlatformGetTls(&_glfw.contextSlot); - if (!window) { - _glfwInputError(GLFW_NO_CURRENT_CONTEXT, "Cannot set swap interval without a current OpenGL or OpenGL ES context"); - return; - } - - window->context.swapInterval(interval); -} - -GLFWAPI int -glfwExtensionSupported(const char *extension) { - _GLFWwindow *window; - assert(extension != NULL); - - _GLFW_REQUIRE_INIT_OR_RETURN(false); - - window = _glfwPlatformGetTls(&_glfw.contextSlot); - if (!window) { - _glfwInputError(GLFW_NO_CURRENT_CONTEXT, "Cannot query extension without a current OpenGL or OpenGL ES context"); - return false; - } - - if (*extension == '\0') { - _glfwInputError(GLFW_INVALID_VALUE, "Extension name cannot be an empty string"); - return false; - } - - if (window->context.major >= 3) { - int i; - GLint count; - - // Check if extension is in the modern OpenGL extensions string list - - window->context.GetIntegerv(GL_NUM_EXTENSIONS, &count); - - for (i = 0; i < count; i++) { - const char *en = (const char *)window->context.GetStringi(GL_EXTENSIONS, i); - if (!en) { - _glfwInputError(GLFW_PLATFORM_ERROR, "Extension string retrieval is broken"); - return false; - } - - if (strcmp(en, extension) == 0) return true; - } - } else { - // Check if extension is in the old style OpenGL extensions string - - const char *extensions = (const char *)window->context.GetString(GL_EXTENSIONS); - if (!extensions) { - _glfwInputError(GLFW_PLATFORM_ERROR, "Extension string retrieval is broken"); - return false; - } - - if (_glfwStringInExtensionString(extension, extensions)) return true; - } - - // Check if extension is in the platform-specific string - return window->context.extensionSupported(extension); -} - -GLFWAPI GLFWglproc -glfwGetProcAddress(const char *procname) { - _GLFWwindow *window; - assert(procname != NULL); - - _GLFW_REQUIRE_INIT_OR_RETURN(NULL); - - window = _glfwPlatformGetTls(&_glfw.contextSlot); - if (!window) { - _glfwInputError(GLFW_NO_CURRENT_CONTEXT, "Cannot query entry point without a current OpenGL or OpenGL ES context"); - return NULL; - } - - return window->context.getProcAddress(procname); -} diff --git a/glfw/egl_context.c b/glfw/egl_context.c deleted file mode 100644 index e939bdd3f..000000000 --- a/glfw/egl_context.c +++ /dev/null @@ -1,642 +0,0 @@ -//======================================================================== -// GLFW 3.4 EGL - www.glfw.org -//------------------------------------------------------------------------ -// Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2019 Camilla Löwy -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would -// be appreciated but is not required. -// -// 2. Altered source versions must be plainly marked as such, and must not -// be misrepresented as being the original software. -// -// 3. This notice may not be removed or altered from any source -// distribution. -// -//======================================================================== -// Please use C89 style variable declarations in this file because VS 2010 -//======================================================================== - -#include "internal.h" - -#include -#include -#include -#include - - -// Return a description of the specified EGL error -// -static const char * -getEGLErrorString(EGLint error) { - switch (error) { - case EGL_SUCCESS: return "Success"; - case EGL_NOT_INITIALIZED: return "EGL is not or could not be initialized"; - case EGL_BAD_ACCESS: return "EGL cannot access a requested resource"; - case EGL_BAD_ALLOC: return "EGL failed to allocate resources for the requested operation"; - case EGL_BAD_ATTRIBUTE: return "An unrecognized attribute or attribute value was passed in the attribute list"; - case EGL_BAD_CONTEXT: return "An EGLContext argument does not name a valid EGL rendering context"; - case EGL_BAD_CONFIG: return "An EGLConfig argument does not name a valid EGL frame buffer configuration"; - case EGL_BAD_CURRENT_SURFACE: return "The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid"; - case EGL_BAD_DISPLAY: return "An EGLDisplay argument does not name a valid EGL display connection"; - case EGL_BAD_SURFACE: return "An EGLSurface argument does not name a valid surface configured for GL rendering"; - case EGL_BAD_MATCH: return "Arguments are inconsistent"; - case EGL_BAD_PARAMETER: return "One or more argument values are invalid"; - case EGL_BAD_NATIVE_PIXMAP: return "A NativePixmapType argument does not refer to a valid native pixmap"; - case EGL_BAD_NATIVE_WINDOW: return "A NativeWindowType argument does not refer to a valid native window"; - case EGL_CONTEXT_LOST: return "The application must destroy all contexts and reinitialise"; - default: return "ERROR: UNKNOWN EGL ERROR"; - } -} - -#ifdef _GLFW_X11 -// Returns the specified attribute of the specified EGLConfig -// -static int -getEGLConfigAttrib(EGLConfig config, int attrib) { - int value; - eglGetConfigAttrib(_glfw.egl.display, config, attrib, &value); - return value; -} -#endif - -// Return the EGLConfig most closely matching the specified hints -// -static bool -chooseEGLConfig(const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *desired, EGLConfig *result) { - EGLConfig configs[512]; - int i = 0, nativeCount = 0, ans_idx = 0; - EGLint attributes[64]; -#define ATTR(k, v) \ - { \ - attributes[i++] = k; \ - attributes[i++] = v; \ - } - ATTR(EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER); - ATTR(EGL_SURFACE_TYPE, EGL_WINDOW_BIT); - if (ctxconfig->client == GLFW_OPENGL_ES_API) { - if (ctxconfig->major == 1) ATTR(EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT) - else ATTR(EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT); - } else if (ctxconfig->client == GLFW_OPENGL_API) ATTR(EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT); - if (desired->samples > 0) ATTR(EGL_SAMPLES, desired->samples); - if (desired->depthBits > 0) ATTR(EGL_DEPTH_SIZE, desired->depthBits); - if (desired->stencilBits > 0) ATTR(EGL_STENCIL_SIZE, desired->stencilBits); - if (desired->redBits > 0) ATTR(EGL_RED_SIZE, desired->redBits); - if (desired->greenBits > 0) ATTR(EGL_GREEN_SIZE, desired->greenBits); - if (desired->blueBits > 0) ATTR(EGL_BLUE_SIZE, desired->blueBits); - if (desired->alphaBits > 0) ATTR(EGL_ALPHA_SIZE, desired->alphaBits); - ATTR(EGL_NONE, EGL_NONE); -#undef ATTR - if (!eglChooseConfig(_glfw.egl.display, attributes, configs, sizeof(configs) / sizeof(configs[0]), &nativeCount)) { - _glfwInputError(GLFW_API_UNAVAILABLE, "EGL: eglChooseConfig failed"); - return false; - } - - if (!nativeCount) { - _glfwInputError(GLFW_API_UNAVAILABLE, "EGL: No EGLConfigs returned"); - return false; - } - - - for (i = 0; i < nativeCount; i++) { -#if defined(_GLFW_X11) - { - const EGLConfig n = configs[i]; - XVisualInfo vi = {0}; - - // Only consider EGLConfigs with associated Visuals - vi.visualid = getEGLConfigAttrib(n, EGL_NATIVE_VISUAL_ID); - if (!vi.visualid) continue; - - if (desired->transparent) { - int count; - XVisualInfo *vis = XGetVisualInfo(_glfw.x11.display, VisualIDMask, &vi, &count); - if (vis) { - bool transparent = _glfwIsVisualTransparentX11(vis[0].visual); - XFree(vis); - if (!transparent) continue; - } - } - } -#endif // _GLFW_X11 - ans_idx = i; - break; - } - *result = configs[ans_idx]; - return true; -} - -static void -makeContextCurrentEGL(_GLFWwindow *window) { - if (window) { - if (!eglMakeCurrent(_glfw.egl.display, window->context.egl.surface, window->context.egl.surface, window->context.egl.handle)) { - _glfwInputError(GLFW_PLATFORM_ERROR, "EGL: Failed to make context current: %s", getEGLErrorString(eglGetError())); - return; - } - } else { - if (!eglMakeCurrent(_glfw.egl.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) { - _glfwInputError(GLFW_PLATFORM_ERROR, "EGL: Failed to clear current context: %s", getEGLErrorString(eglGetError())); - return; - } - } - - _glfwPlatformSetTls(&_glfw.contextSlot, window); -} - -static void -swapBuffersEGL(_GLFWwindow *window) { - if (window != _glfwPlatformGetTls(&_glfw.contextSlot)) { - _glfwInputError(GLFW_PLATFORM_ERROR, "EGL: The context must be current on the calling thread when swapping buffers"); - return; - } - - eglSwapBuffers(_glfw.egl.display, window->context.egl.surface); -} - -static void -swapIntervalEGL(int interval) { - eglSwapInterval(_glfw.egl.display, interval); -} - -static int -extensionSupportedEGL(const char *extension) { - const char *extensions = eglQueryString(_glfw.egl.display, EGL_EXTENSIONS); - if (extensions) { - if (_glfwStringInExtensionString(extension, extensions)) return true; - } - - return false; -} - -static GLFWglproc -getProcAddressEGL(const char *procname) { - _GLFWwindow *window = _glfwPlatformGetTls(&_glfw.contextSlot); - assert(window != NULL); - - if (window->context.egl.client) { - GLFWglproc proc = NULL; - glfw_dlsym(proc, window->context.egl.client, procname); - if (proc) return proc; - } - - return eglGetProcAddress(procname); -} - -static void -destroyContextEGL(_GLFWwindow *window) { -#if defined(_GLFW_X11) - // NOTE: Do not unload libGL.so.1 while the X11 display is still open, - // as it will make XCloseDisplay segfault - if (window->context.client != GLFW_OPENGL_API) -#endif // _GLFW_X11 - { - if (window->context.egl.client) { - _glfw_dlclose(window->context.egl.client); - window->context.egl.client = NULL; - } - } - - if (window->context.egl.surface) { - eglDestroySurface(_glfw.egl.display, window->context.egl.surface); - window->context.egl.surface = EGL_NO_SURFACE; - } - - if (window->context.egl.handle) { - eglDestroyContext(_glfw.egl.display, window->context.egl.handle); - window->context.egl.handle = EGL_NO_CONTEXT; - } -} - - -////////////////////////////////////////////////////////////////////////// -////// GLFW internal API ////// -////////////////////////////////////////////////////////////////////////// - -// Initialize EGL -// -bool -_glfwInitEGL(void) { - int i; - EGLint *attribs = NULL; - const char *extensions; - const char *sonames[] = { -#if defined(_GLFW_EGL_LIBRARY) - _GLFW_EGL_LIBRARY, -#elif defined(_GLFW_WIN32) - "libEGL.dll", - "EGL.dll", -#elif defined(_GLFW_COCOA) - "libEGL.dylib", -#elif defined(__CYGWIN__) - "libEGL-1.so", -#else - "libEGL.so.1", -#endif - NULL}; - - if (_glfw.egl.handle) return true; - - for (i = 0; sonames[i]; i++) { - _glfw.egl.handle = _glfw_dlopen(sonames[i]); - if (_glfw.egl.handle) break; - } - - if (!_glfw.egl.handle) { - _glfwInputError(GLFW_API_UNAVAILABLE, "EGL: Library not found"); - return false; - } - - _glfw.egl.prefix = (strncmp(sonames[i], "lib", 3) == 0); - - glfw_dlsym(_glfw.egl.GetConfigAttrib, _glfw.egl.handle, "eglGetConfigAttrib"); - glfw_dlsym(_glfw.egl.GetConfigs, _glfw.egl.handle, "eglGetConfigs"); - glfw_dlsym(_glfw.egl.ChooseConfig, _glfw.egl.handle, "eglChooseConfig"); - glfw_dlsym(_glfw.egl.GetDisplay, _glfw.egl.handle, "eglGetDisplay"); - glfw_dlsym(_glfw.egl.GetError, _glfw.egl.handle, "eglGetError"); - glfw_dlsym(_glfw.egl.Initialize, _glfw.egl.handle, "eglInitialize"); - glfw_dlsym(_glfw.egl.Terminate, _glfw.egl.handle, "eglTerminate"); - glfw_dlsym(_glfw.egl.BindAPI, _glfw.egl.handle, "eglBindAPI"); - glfw_dlsym(_glfw.egl.CreateContext, _glfw.egl.handle, "eglCreateContext"); - glfw_dlsym(_glfw.egl.DestroySurface, _glfw.egl.handle, "eglDestroySurface"); - glfw_dlsym(_glfw.egl.DestroyContext, _glfw.egl.handle, "eglDestroyContext"); - glfw_dlsym(_glfw.egl.CreateWindowSurface, _glfw.egl.handle, "eglCreateWindowSurface"); - glfw_dlsym(_glfw.egl.MakeCurrent, _glfw.egl.handle, "eglMakeCurrent"); - glfw_dlsym(_glfw.egl.SwapBuffers, _glfw.egl.handle, "eglSwapBuffers"); - glfw_dlsym(_glfw.egl.SwapInterval, _glfw.egl.handle, "eglSwapInterval"); - glfw_dlsym(_glfw.egl.QueryString, _glfw.egl.handle, "eglQueryString"); - glfw_dlsym(_glfw.egl.QuerySurface, _glfw.egl.handle, "eglQuerySurface"); - glfw_dlsym(_glfw.egl.GetProcAddress, _glfw.egl.handle, "eglGetProcAddress"); - - if (!_glfw.egl.GetConfigAttrib || !_glfw.egl.GetConfigs || !_glfw.egl.ChooseConfig || !_glfw.egl.GetDisplay || !_glfw.egl.GetError || - !_glfw.egl.Initialize || !_glfw.egl.Terminate || !_glfw.egl.BindAPI || !_glfw.egl.CreateContext || !_glfw.egl.DestroySurface || - !_glfw.egl.DestroyContext || !_glfw.egl.CreateWindowSurface || !_glfw.egl.MakeCurrent || !_glfw.egl.SwapBuffers || !_glfw.egl.SwapInterval || - !_glfw.egl.QueryString || !_glfw.egl.GetProcAddress) { - _glfwInputError(GLFW_PLATFORM_ERROR, "EGL: Failed to load required entry points"); - - _glfwTerminateEGL(); - return false; - } - - extensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); - if (extensions && eglGetError() == EGL_SUCCESS) _glfw.egl.EXT_client_extensions = true; - - if (_glfw.egl.EXT_client_extensions) { - _glfw.egl.EXT_platform_base = _glfwStringInExtensionString("EGL_EXT_platform_base", extensions); - _glfw.egl.EXT_platform_x11 = _glfwStringInExtensionString("EGL_EXT_platform_x11", extensions); - _glfw.egl.EXT_platform_wayland = _glfwStringInExtensionString("EGL_EXT_platform_wayland", extensions); - _glfw.egl.ANGLE_platform_angle = _glfwStringInExtensionString("EGL_ANGLE_platform_angle", extensions); - _glfw.egl.ANGLE_platform_angle_opengl = _glfwStringInExtensionString("EGL_ANGLE_platform_angle_opengl", extensions); - _glfw.egl.ANGLE_platform_angle_d3d = _glfwStringInExtensionString("EGL_ANGLE_platform_angle_d3d", extensions); - _glfw.egl.ANGLE_platform_angle_vulkan = _glfwStringInExtensionString("EGL_ANGLE_platform_angle_vulkan", extensions); - _glfw.egl.ANGLE_platform_angle_metal = _glfwStringInExtensionString("EGL_ANGLE_platform_angle_metal", extensions); - } - - if (_glfw.egl.EXT_platform_base) { - _glfw.egl.GetPlatformDisplayEXT = (PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT"); - _glfw.egl.CreatePlatformWindowSurfaceEXT = (PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC)eglGetProcAddress("eglCreatePlatformWindowSurfaceEXT"); - } - - _glfw.egl.platform = _glfwPlatformGetEGLPlatform(&attribs); - _glfw.egl.display = EGL_NO_DISPLAY; - if (_glfw.egl.platform) { _glfw.egl.display = eglGetPlatformDisplayEXT(_glfw.egl.platform, _glfwPlatformGetEGLNativeDisplay(), attribs); } - free(attribs); - - if (_glfw.egl.display == EGL_NO_DISPLAY) _glfw.egl.display = eglGetDisplay(_glfwPlatformGetEGLNativeDisplay()); - - - EGLint egl_err; - if (_glfw.egl.display == EGL_NO_DISPLAY && (egl_err = eglGetError()) != EGL_SUCCESS) { - _glfwInputError(GLFW_API_UNAVAILABLE, "EGL: Failed to get EGL display: %s", getEGLErrorString(egl_err)); - - _glfwTerminateEGL(); - return false; - } - - if (!eglInitialize(_glfw.egl.display, &_glfw.egl.major, &_glfw.egl.minor)) { - _glfwInputError( - GLFW_API_UNAVAILABLE, - "EGL: Failed to initialize EGL: %s display_present: %d egl_platform_present: %d", - getEGLErrorString(eglGetError()), - _glfw.egl.display != EGL_NO_DISPLAY, - _glfw.egl.platform != 0); - - _glfwTerminateEGL(); - return false; - } - - _glfw.egl.KHR_create_context = extensionSupportedEGL("EGL_KHR_create_context"); - _glfw.egl.KHR_create_context_no_error = extensionSupportedEGL("EGL_KHR_create_context_no_error"); - _glfw.egl.KHR_gl_colorspace = extensionSupportedEGL("EGL_KHR_gl_colorspace"); - _glfw.egl.KHR_get_all_proc_addresses = extensionSupportedEGL("EGL_KHR_get_all_proc_addresses"); - _glfw.egl.KHR_context_flush_control = extensionSupportedEGL("EGL_KHR_context_flush_control"); - _glfw.egl.EXT_present_opaque = extensionSupportedEGL("EGL_EXT_present_opaque"); - - return true; -} - -// Terminate EGL -// -void -_glfwTerminateEGL(void) { - if (_glfw.egl.display) { - eglTerminate(_glfw.egl.display); - _glfw.egl.display = EGL_NO_DISPLAY; - } - - if (_glfw.egl.handle) { - _glfw_dlclose(_glfw.egl.handle); - _glfw.egl.handle = NULL; - } -} - -#define setAttrib(a, v) \ - { \ - assert(((size_t)index + 1) < sizeof(attribs) / sizeof(attribs[0])); \ - attribs[index++] = a; \ - attribs[index++] = v; \ - } - -// Create the OpenGL or OpenGL ES context -// -bool -_glfwCreateContextEGL(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig) { - EGLint attribs[40]; - EGLConfig config; - EGLContext share = NULL; - EGLNativeWindowType native; - int index = 0; - - if (!_glfw.egl.display) { - _glfwInputError(GLFW_API_UNAVAILABLE, "EGL: API not available"); - return false; - } - - if (ctxconfig->share) share = ctxconfig->share->context.egl.handle; - - if (!chooseEGLConfig(ctxconfig, fbconfig, &config)) { - _glfwInputError(GLFW_FORMAT_UNAVAILABLE, "EGL: Failed to find a suitable EGLConfig"); - return false; - } - - if (ctxconfig->client == GLFW_OPENGL_ES_API) { - if (!eglBindAPI(EGL_OPENGL_ES_API)) { - _glfwInputError(GLFW_API_UNAVAILABLE, "EGL: Failed to bind OpenGL ES: %s", getEGLErrorString(eglGetError())); - return false; - } - } else { - if (!eglBindAPI(EGL_OPENGL_API)) { - _glfwInputError(GLFW_API_UNAVAILABLE, "EGL: Failed to bind OpenGL: %s", getEGLErrorString(eglGetError())); - return false; - } - } - - if (_glfw.egl.KHR_create_context) { - int mask = 0, flags = 0; - - if (ctxconfig->client == GLFW_OPENGL_API) { - if (ctxconfig->forward) flags |= EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR; - - if (ctxconfig->profile == GLFW_OPENGL_CORE_PROFILE) mask |= EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR; - else if (ctxconfig->profile == GLFW_OPENGL_COMPAT_PROFILE) mask |= EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR; - } - - if (ctxconfig->debug) flags |= EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR; - - if (ctxconfig->robustness) { - if (ctxconfig->robustness == GLFW_NO_RESET_NOTIFICATION) { - setAttrib(EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_KHR, EGL_NO_RESET_NOTIFICATION_KHR); - } else if (ctxconfig->robustness == GLFW_LOSE_CONTEXT_ON_RESET) { - setAttrib(EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_KHR, EGL_LOSE_CONTEXT_ON_RESET_KHR); - } - - flags |= EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR; - } - - if (ctxconfig->major != 1 || ctxconfig->minor != 0) { - setAttrib(EGL_CONTEXT_MAJOR_VERSION_KHR, ctxconfig->major); - setAttrib(EGL_CONTEXT_MINOR_VERSION_KHR, ctxconfig->minor); - } - - if (ctxconfig->noerror) { - if (_glfw.egl.KHR_create_context_no_error) setAttrib(EGL_CONTEXT_OPENGL_NO_ERROR_KHR, true); - } - - if (mask) setAttrib(EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR, mask); - - if (flags) setAttrib(EGL_CONTEXT_FLAGS_KHR, flags); - } else { - if (ctxconfig->client == GLFW_OPENGL_ES_API) setAttrib(EGL_CONTEXT_CLIENT_VERSION, ctxconfig->major); - } - - if (_glfw.egl.KHR_context_flush_control) { - if (ctxconfig->release == GLFW_RELEASE_BEHAVIOR_NONE) { - setAttrib(EGL_CONTEXT_RELEASE_BEHAVIOR_KHR, EGL_CONTEXT_RELEASE_BEHAVIOR_NONE_KHR); - } else if (ctxconfig->release == GLFW_RELEASE_BEHAVIOR_FLUSH) { - setAttrib(EGL_CONTEXT_RELEASE_BEHAVIOR_KHR, EGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_KHR); - } - } - - setAttrib(EGL_NONE, EGL_NONE); - - window->context.egl.handle = eglCreateContext(_glfw.egl.display, config, share, attribs); - - if (window->context.egl.handle == EGL_NO_CONTEXT) { - _glfwInputError(GLFW_VERSION_UNAVAILABLE, "EGL: Failed to create context: %s", getEGLErrorString(eglGetError())); - return false; - } - - // Set up attributes for surface creation - index = 0; - - if (fbconfig->sRGB) { - if (_glfw.egl.KHR_gl_colorspace) setAttrib(EGL_GL_COLORSPACE_KHR, EGL_GL_COLORSPACE_SRGB_KHR); - } - // Disabled because it prevents transparency from working on NVIDIA drivers under Wayland - // https://github.com/kovidgoyal/kitty/issues/5479 - // We anyway dont use the alpha bits for anything. - /* if (_glfw.egl.EXT_present_opaque) */ - /* setAttrib(EGL_PRESENT_OPAQUE_EXT, !fbconfig->transparent); */ - - setAttrib(EGL_NONE, EGL_NONE); - - native = _glfwPlatformGetEGLNativeWindow(window); - // HACK: ANGLE does not implement eglCreatePlatformWindowSurfaceEXT - // despite reporting EGL_EXT_platform_base - if (_glfw.egl.platform && _glfw.egl.platform != EGL_PLATFORM_ANGLE_ANGLE) { - window->context.egl.surface = eglCreatePlatformWindowSurfaceEXT(_glfw.egl.display, config, native, attribs); - } else { - window->context.egl.surface = eglCreateWindowSurface(_glfw.egl.display, config, native, attribs); - } - - if (window->context.egl.surface == EGL_NO_SURFACE) { - _glfwInputError(GLFW_PLATFORM_ERROR, "EGL: Failed to create window surface: %s", getEGLErrorString(eglGetError())); - return false; - } - - window->context.egl.config = config; - - EGLint a = EGL_MIN_SWAP_INTERVAL; - if (!eglGetConfigAttrib(_glfw.egl.display, config, a, &a)) { - _glfwInputError(GLFW_VERSION_UNAVAILABLE, "EGL: could not check for non-blocking buffer swap with error: %s", getEGLErrorString(eglGetError())); - } else { - if (a > 0) { _glfwInputError(GLFW_VERSION_UNAVAILABLE, "EGL: non-blocking swap buffers not available, minimum swap interval is: %d", a); } - } - - // Load the appropriate client library - if (!_glfw.egl.KHR_get_all_proc_addresses) { - int i; - const char **sonames; - const char *es1sonames[] = { -#if defined(_GLFW_GLESV1_LIBRARY) - _GLFW_GLESV1_LIBRARY, -#elif defined(_GLFW_WIN32) - "GLESv1_CM.dll", - "libGLES_CM.dll", -#elif defined(_GLFW_COCOA) - "libGLESv1_CM.dylib", -#else - "libGLESv1_CM.so.1", - "libGLES_CM.so.1", -#endif - NULL}; - const char *es2sonames[] = { -#if defined(_GLFW_GLESV2_LIBRARY) - _GLFW_GLESV2_LIBRARY, -#elif defined(_GLFW_WIN32) - "GLESv2.dll", - "libGLESv2.dll", -#elif defined(_GLFW_COCOA) - "libGLESv2.dylib", -#elif defined(__CYGWIN__) - "libGLESv2-2.so", -#else - "libGLESv2.so.2", -#endif - NULL}; - const char *glsonames[] = { -#if defined(_GLFW_OPENGL_LIBRARY) - _GLFW_OPENGL_LIBRARY, -#elif defined(_GLFW_WIN32) -#elif defined(_GLFW_COCOA) -#else - "libGL.so.1", -#endif - NULL}; - - if (ctxconfig->client == GLFW_OPENGL_ES_API) { - if (ctxconfig->major == 1) sonames = es1sonames; - else sonames = es2sonames; - } else sonames = glsonames; - - for (i = 0; sonames[i]; i++) { - // HACK: Match presence of lib prefix to increase chance of finding - // a matching pair in the jungle that is Win32 EGL/GLES - if (_glfw.egl.prefix != (strncmp(sonames[i], "lib", 3) == 0)) continue; - - window->context.egl.client = _glfw_dlopen(sonames[i]); - if (window->context.egl.client) break; - } - - if (!window->context.egl.client) { - _glfwInputError(GLFW_API_UNAVAILABLE, "EGL: Failed to load client library"); - return false; - } - } - - window->context.makeCurrent = makeContextCurrentEGL; - window->context.swapBuffers = swapBuffersEGL; - window->context.swapInterval = swapIntervalEGL; - window->context.extensionSupported = extensionSupportedEGL; - window->context.getProcAddress = getProcAddressEGL; - window->context.destroy = destroyContextEGL; - - return true; -} - -#undef setAttrib - -// Returns the Visual and depth of the chosen EGLConfig -// -#if defined(_GLFW_X11) -bool -_glfwChooseVisualEGL(const _GLFWwndconfig *wndconfig UNUSED, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig, Visual **visual, int *depth) { - XVisualInfo *result; - XVisualInfo desired; - EGLConfig native; - EGLint visualID = 0, count = 0; - const long vimask = VisualScreenMask | VisualIDMask; - - if (!chooseEGLConfig(ctxconfig, fbconfig, &native)) { - _glfwInputError(GLFW_FORMAT_UNAVAILABLE, "EGL: Failed to find a suitable EGLConfig"); - return false; - } - - eglGetConfigAttrib(_glfw.egl.display, native, EGL_NATIVE_VISUAL_ID, &visualID); - - desired.screen = _glfw.x11.screen; - desired.visualid = visualID; - - result = XGetVisualInfo(_glfw.x11.display, vimask, &desired, &count); - if (!result) { - _glfwInputError(GLFW_PLATFORM_ERROR, "EGL: Failed to retrieve Visual for EGLConfig"); - return false; - } - - *visual = result->visual; - *depth = result->depth; - - XFree(result); - return true; -} -#endif // _GLFW_X11 - - -////////////////////////////////////////////////////////////////////////// -////// GLFW native API ////// -////////////////////////////////////////////////////////////////////////// - -GLFWAPI EGLDisplay -glfwGetEGLDisplay(void) { - _GLFW_REQUIRE_INIT_OR_RETURN(EGL_NO_DISPLAY); - return _glfw.egl.display; -} - -GLFWAPI EGLContext -glfwGetEGLContext(GLFWwindow *handle) { - _GLFWwindow *window = (_GLFWwindow *)handle; - assert(window != NULL); - - _GLFW_REQUIRE_INIT_OR_RETURN(EGL_NO_CONTEXT); - - if (window->context.client == GLFW_NO_API) { - _glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL); - return EGL_NO_CONTEXT; - } - - return window->context.egl.handle; -} - -GLFWAPI EGLSurface -glfwGetEGLSurface(GLFWwindow *handle) { - _GLFWwindow *window = (_GLFWwindow *)handle; - assert(window != NULL); - - _GLFW_REQUIRE_INIT_OR_RETURN(EGL_NO_SURFACE); - - if (window->context.client == GLFW_NO_API) { - _glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL); - return EGL_NO_SURFACE; - } - - return window->context.egl.surface; -} diff --git a/glfw/egl_context.h b/glfw/egl_context.h deleted file mode 100644 index 3ab62075d..000000000 --- a/glfw/egl_context.h +++ /dev/null @@ -1,228 +0,0 @@ -//======================================================================== -// GLFW 3.4 EGL - www.glfw.org -//------------------------------------------------------------------------ -// Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2017 Camilla Löwy -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would -// be appreciated but is not required. -// -// 2. Altered source versions must be plainly marked as such, and must not -// be misrepresented as being the original software. -// -// 3. This notice may not be removed or altered from any source -// distribution. -// -//======================================================================== - -#if defined(_GLFW_WIN32) -#define EGLAPIENTRY __stdcall -#else -#define EGLAPIENTRY -#endif - -#define EGL_SUCCESS 0x3000 -#define EGL_NOT_INITIALIZED 0x3001 -#define EGL_BAD_ACCESS 0x3002 -#define EGL_BAD_ALLOC 0x3003 -#define EGL_BAD_ATTRIBUTE 0x3004 -#define EGL_BAD_CONFIG 0x3005 -#define EGL_BAD_CONTEXT 0x3006 -#define EGL_BAD_CURRENT_SURFACE 0x3007 -#define EGL_BAD_DISPLAY 0x3008 -#define EGL_BAD_MATCH 0x3009 -#define EGL_BAD_NATIVE_PIXMAP 0x300a -#define EGL_BAD_NATIVE_WINDOW 0x300b -#define EGL_BAD_PARAMETER 0x300c -#define EGL_BAD_SURFACE 0x300d -#define EGL_CONTEXT_LOST 0x300e -#define EGL_COLOR_BUFFER_TYPE 0x303f -#define EGL_RGB_BUFFER 0x308e -#define EGL_SURFACE_TYPE 0x3033 -#define EGL_WINDOW_BIT 0x0004 -#define EGL_RENDERABLE_TYPE 0x3040 -#define EGL_OPENGL_ES_BIT 0x0001 -#define EGL_OPENGL_ES2_BIT 0x0004 -#define EGL_OPENGL_BIT 0x0008 -#define EGL_ALPHA_SIZE 0x3021 -#define EGL_BLUE_SIZE 0x3022 -#define EGL_GREEN_SIZE 0x3023 -#define EGL_RED_SIZE 0x3024 -#define EGL_DEPTH_SIZE 0x3025 -#define EGL_STENCIL_SIZE 0x3026 -#define EGL_SAMPLES 0x3031 -#define EGL_OPENGL_ES_API 0x30a0 -#define EGL_OPENGL_API 0x30a2 -#define EGL_NONE 0x3038 -#define EGL_EXTENSIONS 0x3055 -#define EGL_CONTEXT_CLIENT_VERSION 0x3098 -#define EGL_NATIVE_VISUAL_ID 0x302e -#define EGL_NO_SURFACE ((EGLSurface)0) -#define EGL_NO_DISPLAY ((EGLDisplay)0) -#define EGL_NO_CONTEXT ((EGLContext)0) -#define EGL_DEFAULT_DISPLAY ((EGLNativeDisplayType)0) -#define EGL_MIN_SWAP_INTERVAL 0x303B -#define EGL_MAX_SWAP_INTERVAL 0x303C - -#define EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR 0x00000002 -#define EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR 0x00000001 -#define EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR 0x00000002 -#define EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR 0x00000001 -#define EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_KHR 0x31bd -#define EGL_NO_RESET_NOTIFICATION_KHR 0x31be -#define EGL_LOSE_CONTEXT_ON_RESET_KHR 0x31bf -#define EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR 0x00000004 -#define EGL_CONTEXT_MAJOR_VERSION_KHR 0x3098 -#define EGL_CONTEXT_MINOR_VERSION_KHR 0x30fb -#define EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR 0x30fd -#define EGL_CONTEXT_FLAGS_KHR 0x30fc -#define EGL_CONTEXT_OPENGL_NO_ERROR_KHR 0x31b3 -#define EGL_GL_COLORSPACE_KHR 0x309d -#define EGL_GL_COLORSPACE_SRGB_KHR 0x3089 -#define EGL_CONTEXT_RELEASE_BEHAVIOR_KHR 0x2097 -#define EGL_CONTEXT_RELEASE_BEHAVIOR_NONE_KHR 0 -#define EGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_KHR 0x2098 -#define EGL_PLATFORM_X11_EXT 0x31d5 -#define EGL_PLATFORM_WAYLAND_EXT 0x31d8 -#define EGL_PLATFORM_ANGLE_ANGLE 0x3202 -#define EGL_PLATFORM_ANGLE_TYPE_ANGLE 0x3203 -#define EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE 0x320d -#define EGL_PLATFORM_ANGLE_TYPE_OPENGLES_ANGLE 0x320e -#define EGL_PLATFORM_ANGLE_TYPE_D3D9_ANGLE 0x3207 -#define EGL_PLATFORM_ANGLE_TYPE_D3D11_ANGLE 0x3208 -#define EGL_PLATFORM_ANGLE_TYPE_VULKAN_ANGLE 0x3450 -#define EGL_PLATFORM_ANGLE_TYPE_METAL_ANGLE 0x3489 -#define EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE 0x348f - -typedef int EGLint; -typedef unsigned int EGLBoolean; -typedef unsigned int EGLenum; -typedef void *EGLConfig; -typedef void *EGLContext; -typedef void *EGLDisplay; -typedef void *EGLSurface; - -typedef void *EGLNativeDisplayType; -typedef void *EGLNativeWindowType; - -// EGL function pointer typedefs -typedef EGLBoolean(EGLAPIENTRY *PFN_eglGetConfigAttrib)(EGLDisplay, EGLConfig, EGLint, EGLint *); -typedef EGLBoolean(EGLAPIENTRY *PFN_eglGetConfigs)(EGLDisplay, EGLConfig *, EGLint, EGLint *); -typedef EGLBoolean(EGLAPIENTRY *PFN_eglChooseConfig)(EGLDisplay, EGLint const *, EGLConfig *, EGLint, EGLint *); -typedef EGLDisplay(EGLAPIENTRY *PFN_eglGetDisplay)(EGLNativeDisplayType); -typedef EGLint(EGLAPIENTRY *PFN_eglGetError)(void); -typedef EGLBoolean(EGLAPIENTRY *PFN_eglInitialize)(EGLDisplay, EGLint *, EGLint *); -typedef EGLBoolean(EGLAPIENTRY *PFN_eglTerminate)(EGLDisplay); -typedef EGLBoolean(EGLAPIENTRY *PFN_eglBindAPI)(EGLenum); -typedef EGLContext(EGLAPIENTRY *PFN_eglCreateContext)(EGLDisplay, EGLConfig, EGLContext, const EGLint *); -typedef EGLBoolean(EGLAPIENTRY *PFN_eglDestroySurface)(EGLDisplay, EGLSurface); -typedef EGLBoolean(EGLAPIENTRY *PFN_eglDestroyContext)(EGLDisplay, EGLContext); -typedef EGLSurface(EGLAPIENTRY *PFN_eglCreateWindowSurface)(EGLDisplay, EGLConfig, EGLNativeWindowType, const EGLint *); -typedef EGLBoolean(EGLAPIENTRY *PFN_eglMakeCurrent)(EGLDisplay, EGLSurface, EGLSurface, EGLContext); -typedef EGLBoolean(EGLAPIENTRY *PFN_eglSwapBuffers)(EGLDisplay, EGLSurface); -typedef EGLBoolean(EGLAPIENTRY *PFN_eglSwapInterval)(EGLDisplay, EGLint); -typedef const char *(EGLAPIENTRY *PFN_eglQueryString)(EGLDisplay, EGLint); -typedef const char *(EGLAPIENTRY *PFN_eglQuerySurface)(EGLDisplay, EGLSurface, EGLint, EGLint *); -typedef GLFWglproc(EGLAPIENTRY *PFN_eglGetProcAddress)(const char *); -#define eglGetConfigAttrib _glfw.egl.GetConfigAttrib -#define eglGetConfigs _glfw.egl.GetConfigs -#define eglChooseConfig _glfw.egl.ChooseConfig -#define eglGetDisplay _glfw.egl.GetDisplay -#define eglGetError _glfw.egl.GetError -#define eglInitialize _glfw.egl.Initialize -#define eglTerminate _glfw.egl.Terminate -#define eglBindAPI _glfw.egl.BindAPI -#define eglCreateContext _glfw.egl.CreateContext -#define eglDestroySurface _glfw.egl.DestroySurface -#define eglDestroyContext _glfw.egl.DestroyContext -#define eglCreateWindowSurface _glfw.egl.CreateWindowSurface -#define eglMakeCurrent _glfw.egl.MakeCurrent -#define eglSwapBuffers _glfw.egl.SwapBuffers -#define eglSwapInterval _glfw.egl.SwapInterval -#define eglQueryString _glfw.egl.QueryString -#define eglQuerySurface _glfw.egl.QuerySurface -#define eglGetProcAddress _glfw.egl.GetProcAddress - -typedef EGLDisplay(EGLAPIENTRY *PFNEGLGETPLATFORMDISPLAYEXTPROC)(EGLenum, void *, const EGLint *); -typedef EGLSurface(EGLAPIENTRY *PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC)(EGLDisplay, EGLConfig, void *, const EGLint *); -#define eglGetPlatformDisplayEXT _glfw.egl.GetPlatformDisplayEXT -#define eglCreatePlatformWindowSurfaceEXT _glfw.egl.CreatePlatformWindowSurfaceEXT - -// EGL-specific per-context data -// -typedef struct _GLFWcontextEGL { - EGLConfig config; - EGLContext handle; - EGLSurface surface; - - void *client; - -} _GLFWcontextEGL; - -// EGL-specific global data -// -typedef struct _GLFWlibraryEGL { - EGLenum platform; - EGLDisplay display; - EGLint major, minor; - bool prefix; - - bool KHR_create_context; - bool KHR_create_context_no_error; - bool KHR_gl_colorspace; - bool KHR_get_all_proc_addresses; - bool KHR_context_flush_control; - bool EXT_client_extensions; - bool EXT_platform_base; - bool EXT_platform_x11; - bool EXT_platform_wayland; - bool EXT_present_opaque; - bool ANGLE_platform_angle; - bool ANGLE_platform_angle_opengl; - bool ANGLE_platform_angle_d3d; - bool ANGLE_platform_angle_vulkan; - bool ANGLE_platform_angle_metal; - - void *handle; - - PFN_eglGetConfigAttrib GetConfigAttrib; - PFN_eglGetConfigs GetConfigs; - PFN_eglChooseConfig ChooseConfig; - PFN_eglGetDisplay GetDisplay; - PFN_eglGetError GetError; - PFN_eglInitialize Initialize; - PFN_eglTerminate Terminate; - PFN_eglBindAPI BindAPI; - PFN_eglCreateContext CreateContext; - PFN_eglDestroySurface DestroySurface; - PFN_eglDestroyContext DestroyContext; - PFN_eglCreateWindowSurface CreateWindowSurface; - PFN_eglMakeCurrent MakeCurrent; - PFN_eglSwapBuffers SwapBuffers; - PFN_eglSwapInterval SwapInterval; - PFN_eglQueryString QueryString; - PFN_eglQuerySurface QuerySurface; - PFN_eglGetProcAddress GetProcAddress; - - PFNEGLGETPLATFORMDISPLAYEXTPROC GetPlatformDisplayEXT; - PFNEGLCREATEPLATFORMWINDOWSURFACEEXTPROC CreatePlatformWindowSurfaceEXT; - -} _GLFWlibraryEGL; - - -bool _glfwInitEGL(void); -void _glfwTerminateEGL(void); -bool _glfwCreateContextEGL(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig); -#if defined(_GLFW_X11) -bool _glfwChooseVisualEGL(const _GLFWwndconfig *wndconfig, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig, Visual **visual, int *depth); -#endif /*_GLFW_X11*/ diff --git a/glfw/glfw.py b/glfw/glfw.py index 4bca08fec..cbd2aeec3 100755 --- a/glfw/glfw.py +++ b/glfw/glfw.py @@ -78,7 +78,7 @@ def generate_wrappers(glfw_header: str) -> None: functions.append(Function(decl)) for line in """\ void* glfwGetCocoaWindow(GLFWwindow* window) - void* glfwGetNSGLContext(GLFWwindow *window) + void* glfwGetCocoaView(GLFWwindow* window) uint32_t glfwGetCocoaMonitor(GLFWmonitor* monitor) GLFWcocoatextinputfilterfun glfwSetCocoaTextInputFilter(GLFWwindow* window, GLFWcocoatextinputfilterfun callback) GLFWhandleurlopen glfwSetCocoaURLOpenCallback(GLFWhandleurlopen callback) @@ -87,10 +87,13 @@ def generate_wrappers(glfw_header: str) -> None: GLFWapplicationwillfinishlaunchingfun glfwSetApplicationWillFinishLaunching(GLFWapplicationwillfinishlaunchingfun callback) uint32_t glfwGetCocoaKeyEquivalent(uint32_t glfw_key, int glfw_mods, int* cocoa_mods) void glfwCocoaRequestRenderFrame(GLFWwindow *w, GLFWcocoarenderframefun callback) - bool glfwCocoaRecreateGLDrawable(GLFWwindow *w) GLFWcocoarenderframefun glfwCocoaSetWindowResizeCallback(GLFWwindow *w, GLFWcocoarenderframefun callback) void* glfwGetX11Display(void) unsigned long glfwGetX11Window(GLFWwindow* window) + void glfwX11PushErrorTrap(void) + int glfwX11PopErrorTrap(void) + void* glfwGetWaylandDisplay(void) + void* glfwGetWaylandWindow(GLFWwindow* window) void glfwSetPrimarySelectionString(GLFWwindow* window, const char* string) void glfwCocoaCycleThroughOSWindows(bool backwards) void glfwCocoaSetWindowChrome(GLFWwindow* window, unsigned int color, bool use_system_color, unsigned int system_color,\ diff --git a/glfw/glfw3.h b/glfw/glfw3.h index 4bfd45d9f..6d6dccfd1 100644 --- a/glfw/glfw3.h +++ b/glfw/glfw3.h @@ -46,12 +46,6 @@ extern "C" { * * For more information about how to use this file, see @ref build_include. */ -/*! @defgroup context Context reference - * @brief Functions and types related to OpenGL and OpenGL ES contexts. - * - * This is the reference documentation for OpenGL and OpenGL ES context related - * functions. For more task-oriented information, see the @ref context_guide. - */ /*! @defgroup vulkan Vulkan reference * @brief Functions and types related to Vulkan. * @@ -153,96 +147,6 @@ typedef intptr_t ssize_t; #define GLFW_CALLBACK_DEFINED #endif /* CALLBACK */ -/* Include the chosen OpenGL or OpenGL ES headers. - */ -#if defined(GLFW_INCLUDE_ES1) - -#include -#if defined(GLFW_INCLUDE_GLEXT) -#include -#endif - -#elif defined(GLFW_INCLUDE_ES2) - -#include -#if defined(GLFW_INCLUDE_GLEXT) -#include -#endif - -#elif defined(GLFW_INCLUDE_ES3) - -#include -#if defined(GLFW_INCLUDE_GLEXT) -#include -#endif - -#elif defined(GLFW_INCLUDE_ES31) - -#include -#if defined(GLFW_INCLUDE_GLEXT) -#include -#endif - -#elif defined(GLFW_INCLUDE_ES32) - -#include -#if defined(GLFW_INCLUDE_GLEXT) -#include -#endif - -#elif defined(GLFW_INCLUDE_GLCOREARB) - -#if defined(__APPLE__) - -#include -#if defined(GLFW_INCLUDE_GLEXT) -#include -#endif /*GLFW_INCLUDE_GLEXT*/ - -#else /*__APPLE__*/ - -#include - -#endif /*__APPLE__*/ - -#elif defined(GLFW_INCLUDE_GLU) - -#if defined(__APPLE__) - -#if defined(GLFW_INCLUDE_GLU) -#include -#endif - -#else /*__APPLE__*/ - -#if defined(GLFW_INCLUDE_GLU) -#include -#endif - -#endif /*__APPLE__*/ - -#elif !defined(GLFW_INCLUDE_NONE) && !defined(__gl_h_) && !defined(__gles1_gl_h_) && !defined(__gles2_gl2_h_) && !defined(__gles2_gl3_h_) && \ - !defined(__gles2_gl31_h_) && !defined(__gles2_gl32_h_) && !defined(__gl_glcorearb_h_) && !defined(__gl2_h_) /*legacy*/ && !defined(__gl3_h_) /*legacy*/ && \ - !defined(__gl31_h_) /*legacy*/ && !defined(__gl32_h_) /*legacy*/ && !defined(__glcorearb_h_) /*legacy*/ && !defined(__GL_H__) /*non-standard*/ && \ - !defined(__gltypes_h_) /*non-standard*/ && !defined(__glee_h_) /*non-standard*/ - -#if defined(__APPLE__) - -#if !defined(GLFW_INCLUDE_GLEXT) -#define GL_GLEXT_LEGACY -#endif -#include - -#else /*__APPLE__*/ - -#include -#if defined(GLFW_INCLUDE_GLEXT) -#include -#endif - -#endif /*__APPLE__*/ - -#endif /* OpenGL and OpenGL ES headers */ #if defined(GLFW_DLL) && defined(_GLFW_BUILD_DLL) /* GLFW_DLL must be defined by applications that are linking against the DLL @@ -713,16 +617,6 @@ typedef struct GLFWTouchEvent { * function that requires initialization. */ #define GLFW_NOT_INITIALIZED 0x00010001 -/*! @brief No context is current for this thread. - * - * This occurs if a GLFW function was called that needs and operates on the - * current OpenGL or OpenGL ES context but no context is current on the calling - * thread. One such function is @ref glfwSwapInterval. - * - * @analysis Application programmer error. Ensure a context is current before - * calling functions that require a current context. - */ -#define GLFW_NO_CURRENT_CONTEXT 0x00010002 /*! @brief One of the arguments to the function was an invalid enum value. * * One of the arguments to the function was an invalid enum value, for example @@ -813,14 +707,6 @@ typedef struct GLFWTouchEvent { * the user, as appropriate. */ #define GLFW_FORMAT_UNAVAILABLE 0x00010009 -/*! @brief The specified window does not have an OpenGL or OpenGL ES context. - * - * A window that does not have an OpenGL or OpenGL ES context was passed to - * a function that requires it to have one. - * - * @analysis Application programmer error. Fix the offending call. - */ -#define GLFW_NO_WINDOW_CONTEXT 0x0001000A /*! @brief The requested feature is not provided by the platform. * * The requested feature is not provided by the platform, so GLFW is unable to @@ -935,158 +821,12 @@ typedef struct GLFWTouchEvent { * Occlusion [window attribute](@ref GLFW_OCCLUDED_attrib). */ #define GLFW_OCCLUDED 0x0002000E -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_RED_BITS). - */ -#define GLFW_RED_BITS 0x00021001 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_GREEN_BITS). - */ -#define GLFW_GREEN_BITS 0x00021002 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_BLUE_BITS). - */ -#define GLFW_BLUE_BITS 0x00021003 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_ALPHA_BITS). - */ -#define GLFW_ALPHA_BITS 0x00021004 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_DEPTH_BITS). - */ -#define GLFW_DEPTH_BITS 0x00021005 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_STENCIL_BITS). - */ -#define GLFW_STENCIL_BITS 0x00021006 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_ACCUM_RED_BITS). - */ -#define GLFW_ACCUM_RED_BITS 0x00021007 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_ACCUM_GREEN_BITS). - */ -#define GLFW_ACCUM_GREEN_BITS 0x00021008 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_ACCUM_BLUE_BITS). - */ -#define GLFW_ACCUM_BLUE_BITS 0x00021009 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_ACCUM_ALPHA_BITS). - */ -#define GLFW_ACCUM_ALPHA_BITS 0x0002100A -/*! @brief Framebuffer auxiliary buffer hint. - * - * Framebuffer auxiliary buffer [hint](@ref GLFW_AUX_BUFFERS). - */ -#define GLFW_AUX_BUFFERS 0x0002100B -/*! @brief OpenGL stereoscopic rendering hint. - * - * OpenGL stereoscopic rendering [hint](@ref GLFW_STEREO). - */ -#define GLFW_STEREO 0x0002100C -/*! @brief Framebuffer MSAA samples hint. - * - * Framebuffer MSAA samples [hint](@ref GLFW_SAMPLES). - */ -#define GLFW_SAMPLES 0x0002100D -/*! @brief Framebuffer sRGB hint. - * - * Framebuffer sRGB [hint](@ref GLFW_SRGB_CAPABLE). - */ -#define GLFW_SRGB_CAPABLE 0x0002100E /*! @brief Monitor refresh rate hint. * * Monitor refresh rate [hint](@ref GLFW_REFRESH_RATE). */ #define GLFW_REFRESH_RATE 0x0002100F -/*! @brief Framebuffer double buffering hint. - * - * Framebuffer double buffering [hint](@ref GLFW_DOUBLEBUFFER). - */ -#define GLFW_DOUBLEBUFFER 0x00021010 -/*! @brief Context client API hint and attribute. - * - * Context client API [hint](@ref GLFW_CLIENT_API_hint) and - * [attribute](@ref GLFW_CLIENT_API_attrib). - */ -#define GLFW_CLIENT_API 0x00022001 -/*! @brief Context client API major version hint and attribute. - * - * Context client API major version [hint](@ref GLFW_CONTEXT_VERSION_MAJOR_hint) - * and [attribute](@ref GLFW_CONTEXT_VERSION_MAJOR_attrib). - */ -#define GLFW_CONTEXT_VERSION_MAJOR 0x00022002 -/*! @brief Context client API minor version hint and attribute. - * - * Context client API minor version [hint](@ref GLFW_CONTEXT_VERSION_MINOR_hint) - * and [attribute](@ref GLFW_CONTEXT_VERSION_MINOR_attrib). - */ -#define GLFW_CONTEXT_VERSION_MINOR 0x00022003 -/*! @brief Context client API revision number hint and attribute. - * - * Context client API revision number - * [attribute](@ref GLFW_CONTEXT_REVISION_attrib). - */ -#define GLFW_CONTEXT_REVISION 0x00022004 -/*! @brief Context robustness hint and attribute. - * - * Context client API revision number [hint](@ref GLFW_CONTEXT_ROBUSTNESS_hint) - * and [attribute](@ref GLFW_CONTEXT_ROBUSTNESS_attrib). - */ -#define GLFW_CONTEXT_ROBUSTNESS 0x00022005 -/*! @brief OpenGL forward-compatibility hint and attribute. - * - * OpenGL forward-compatibility [hint](@ref GLFW_OPENGL_FORWARD_COMPAT_hint) - * and [attribute](@ref GLFW_OPENGL_FORWARD_COMPAT_attrib). - */ -#define GLFW_OPENGL_FORWARD_COMPAT 0x00022006 -/*! @brief Debug mode context hint and attribute. - * - * Debug mode context [hint](@ref GLFW_CONTEXT_DEBUG_hint) and - * [attribute](@ref GLFW_CONTEXT_DEBUG_attrib). - */ -#define GLFW_CONTEXT_DEBUG 0x00022007 -/*! @brief Legacy name for compatibility. - * - * This is an alias for compatibility with earlier versions. - */ -#define GLFW_OPENGL_DEBUG_CONTEXT GLFW_CONTEXT_DEBUG -/*! @brief OpenGL profile hint and attribute. - * - * OpenGL profile [hint](@ref GLFW_OPENGL_PROFILE_hint) and - * [attribute](@ref GLFW_OPENGL_PROFILE_attrib). - */ -#define GLFW_OPENGL_PROFILE 0x00022008 -/*! @brief Context flush-on-release hint and attribute. - * - * Context flush-on-release [hint](@ref GLFW_CONTEXT_RELEASE_BEHAVIOR_hint) and - * [attribute](@ref GLFW_CONTEXT_RELEASE_BEHAVIOR_attrib). - */ -#define GLFW_CONTEXT_RELEASE_BEHAVIOR 0x00022009 -/*! @brief Context error suppression hint and attribute. - * - * Context error suppression [hint](@ref GLFW_CONTEXT_NO_ERROR_hint) and - * [attribute](@ref GLFW_CONTEXT_NO_ERROR_attrib). - */ -#define GLFW_CONTEXT_NO_ERROR 0x0002200A -/*! @brief Context creation API hint and attribute. - * - * Context creation API [hint](@ref GLFW_CONTEXT_CREATION_API_hint) and - * [attribute](@ref GLFW_CONTEXT_CREATION_API_attrib). - */ -#define GLFW_CONTEXT_CREATION_API 0x0002200B /*! @brief Window content area scaling window * [window hint](@ref GLFW_SCALE_TO_MONITOR). */ @@ -1099,10 +839,6 @@ typedef struct GLFWTouchEvent { * [window hint](@ref GLFW_COCOA_FRAME_NAME_hint). */ #define GLFW_COCOA_FRAME_NAME 0x00023002 -/*! @brief macOS specific - * [window hint](@ref GLFW_COCOA_GRAPHICS_SWITCHING_hint). - */ -#define GLFW_COCOA_GRAPHICS_SWITCHING 0x00023003 /*! @brief macOS specific * [window hint](@ref GLFW_COCOA_COLOR_SPACE_hint). */ @@ -1125,23 +861,17 @@ typedef enum { * [window hint](@ref GLFW_X11_CLASS_NAME_hint). */ #define GLFW_X11_INSTANCE_NAME 0x00024002 +/*! @brief X11 specific + * The id of the X11 visual to use for the window, as chosen by the GPU driver, + * zero for the default visual. + */ +#define GLFW_X11_VISUAL_ID 0x00024003 #define GLFW_WAYLAND_APP_ID 0x00025001 #define GLFW_WAYLAND_BGCOLOR 0x00025002 #define GLFW_WAYLAND_WINDOW_TAG 0x00025003 /*! @} */ -#define GLFW_NO_API 0 -#define GLFW_OPENGL_API 0x00030001 -#define GLFW_OPENGL_ES_API 0x00030002 - -#define GLFW_NO_ROBUSTNESS 0 -#define GLFW_NO_RESET_NOTIFICATION 0x00031001 -#define GLFW_LOSE_CONTEXT_ON_RESET 0x00031002 - -#define GLFW_OPENGL_ANY_PROFILE 0 -#define GLFW_OPENGL_CORE_PROFILE 0x00032001 -#define GLFW_OPENGL_COMPAT_PROFILE 0x00032002 #define GLFW_CURSOR 0x00033001 #define GLFW_STICKY_KEYS 0x00033002 @@ -1153,21 +883,6 @@ typedef enum { #define GLFW_CURSOR_HIDDEN 0x00034002 #define GLFW_CURSOR_DISABLED 0x00034003 -#define GLFW_ANY_RELEASE_BEHAVIOR 0 -#define GLFW_RELEASE_BEHAVIOR_FLUSH 0x00035001 -#define GLFW_RELEASE_BEHAVIOR_NONE 0x00035002 - -#define GLFW_NATIVE_CONTEXT_API 0x00036001 -#define GLFW_EGL_CONTEXT_API 0x00036002 -#define GLFW_OSMESA_CONTEXT_API 0x00036003 - -#define GLFW_ANGLE_PLATFORM_TYPE_NONE 0x00037001 -#define GLFW_ANGLE_PLATFORM_TYPE_OPENGL 0x00037002 -#define GLFW_ANGLE_PLATFORM_TYPE_OPENGLES 0x00037003 -#define GLFW_ANGLE_PLATFORM_TYPE_D3D9 0x00037004 -#define GLFW_ANGLE_PLATFORM_TYPE_D3D11 0x00037005 -#define GLFW_ANGLE_PLATFORM_TYPE_VULKAN 0x00037007 -#define GLFW_ANGLE_PLATFORM_TYPE_METAL 0x00037008 /*! @defgroup shapes Standard cursor shapes * @brief Standard system cursor shapes. @@ -1224,11 +939,6 @@ typedef enum { * Joystick hat buttons [init hint](@ref GLFW_JOYSTICK_HAT_BUTTONS). */ #define GLFW_JOYSTICK_HAT_BUTTONS 0x00050001 -/*! @brief ANGLE rendering backend init hint. - * - * ANGLE rendering backend [init hint](@ref GLFW_ANGLE_PLATFORM_TYPE_hint). - */ -#define GLFW_ANGLE_PLATFORM_TYPE 0x00050002 #define GLFW_DEBUG_KEYBOARD 0x00050003 #define GLFW_DEBUG_RENDERING 0x00050004 /*! @brief macOS specific init hint. @@ -1251,20 +961,6 @@ typedef enum { * GLFW API types *************************************************************************/ -/*! @brief Client API function pointer type. - * - * Generic function pointer used for returning client API function pointers - * without forcing a cast from a regular pointer. - * - * @sa @ref context_glext - * @sa @ref glfwGetProcAddress - * - * @since Added in version 3.0. - * - * @ingroup context - */ -typedef void (*GLFWglproc)(void); - /*! @brief Vulkan API function pointer type. * * Generic function pointer used for returning Vulkan API function pointers @@ -1728,6 +1424,14 @@ typedef void (*GLFWwindowmaximizefun)(GLFWwindow *, int); */ typedef void (*GLFWframebuffersizefun)(GLFWwindow *, int, int); +/*! @brief The function pointer type for native surface change callbacks. + * + * Called when the native surface a window renders into changes in a way that + * requires the GPU driver to update its drawable, such as on macOS when the + * view is resized or moved to a different screen. + */ +typedef void (*GLFWnativesurfacechangedfun)(GLFWwindow *); + /*! @brief The function pointer type for window content scale callbacks. * * This is the function pointer type for window content scale callbacks. @@ -2953,7 +2657,12 @@ GLFWAPI void glfwWindowHint(int hint, int value); */ GLFWAPI void glfwWindowHintString(int hint, const char *value); -/*! @brief Creates a window and its associated context. +/*! @brief Creates a window. + * + * GLFW does not create any GPU contexts or surfaces for the window, that is + * the responsibility of the GPU driver, which renders into the native window, + * see glfwGetX11Window(), glfwGetWaylandWindow() and glfwGetCocoaView(). + * The documentation below about contexts is obsolete. * * This function creates a window and its associated OpenGL or OpenGL ES * context. Most of the options controlling how the window and its context @@ -3011,8 +2720,6 @@ GLFWAPI void glfwWindowHintString(int hint, const char *value); * @param[in] title The initial, UTF-8 encoded window title. * @param[in] monitor The monitor to use for full screen mode, or `NULL` for * windowed mode. - * @param[in] share The window whose context to share resources with, or `NULL` - * to not share resources. * @return The handle of the created window, or `NULL` if an * [error](@ref error_handling) occurred. * @@ -3105,7 +2812,7 @@ GLFWAPI void glfwWindowHintString(int hint, const char *value); * * @ingroup window */ -GLFWAPI GLFWwindow *glfwCreateWindow(int width, int height, const char *title, GLFWmonitor *monitor, GLFWwindow *share, const GLFWLayerShellConfig *lsc); +GLFWAPI GLFWwindow *glfwCreateWindow(int width, int height, const char *title, GLFWmonitor *monitor, const GLFWLayerShellConfig *lsc); GLFWAPI bool glfwToggleFullscreen(GLFWwindow *window, unsigned int flags); GLFWAPI bool glfwIsFullscreen(GLFWwindow *window, unsigned int flags); GLFWAPI bool glfwAreSwapsAllowed(const GLFWwindow *window); @@ -4426,6 +4133,29 @@ GLFWAPI GLFWwindowmaximizefun glfwSetWindowMaximizeCallback(GLFWwindow *window, */ GLFWAPI GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow *window, GLFWframebuffersizefun callback); +/*! @brief Sets the native surface change callback for the specified window. + * + * @param[in] window The window whose callback to set. + * @param[in] callback The new callback, or `NULL` to remove the currently set + * callback. + * @return The previously set callback. + * + * @sa GLFWnativesurfacechangedfun + * @ingroup window + */ +GLFWAPI GLFWnativesurfacechangedfun glfwSetNativeSurfaceChangedCallback(GLFWwindow *window, GLFWnativesurfacechangedfun callback); + +/*! @brief Notify GLFW that the contents of the window were presented. + * + * Must be called after the GPU driver presents a new frame for the window. + * On Wayland this commits pending surface state that must be committed + * together with a new buffer. + * + * @param[in] window The window that was presented. + * @ingroup window + */ +GLFWAPI void glfwWindowContentsPresented(GLFWwindow *window); + /*! @brief Sets the window content scale callback for the specified window. * * This function sets the window content scale callback of the specified window, @@ -5611,225 +5341,6 @@ GLFWAPI void glfwGetClipboard(GLFWClipboardType clipboard_type, const char *mime */ GLFWAPI monotonic_t glfwGetTime(void); -/*! @brief Makes the context of the specified window current for the calling - * thread. - * - * This function makes the OpenGL or OpenGL ES context of the specified window - * current on the calling thread. A context must only be made current on - * a single thread at a time and each thread can have only a single current - * context at a time. - * - * When moving a context between threads, you must make it non-current on the - * old thread before making it current on the new one. - * - * By default, making a context non-current implicitly forces a pipeline flush. - * On machines that support `GL_KHR_context_flush_control`, you can control - * whether a context performs this flush by setting the - * [GLFW_CONTEXT_RELEASE_BEHAVIOR](@ref GLFW_CONTEXT_RELEASE_BEHAVIOR_hint) - * hint. - * - * The specified window must have an OpenGL or OpenGL ES context. Specifying - * a window without a context will generate a @ref GLFW_NO_WINDOW_CONTEXT - * error. - * - * @param[in] window The window whose context to make current, or `NULL` to - * detach the current context. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_NO_WINDOW_CONTEXT and @ref GLFW_PLATFORM_ERROR. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref context_current - * @sa @ref glfwGetCurrentContext - * - * @since Added in version 3.0. - * - * @ingroup context - */ -GLFWAPI void glfwMakeContextCurrent(GLFWwindow *window); - -/*! @brief Returns the window whose context is current on the calling thread. - * - * This function returns the window whose OpenGL or OpenGL ES context is - * current on the calling thread. - * - * @return The window whose context is current, or `NULL` if no window's - * context is current. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref context_current - * @sa @ref glfwMakeContextCurrent - * - * @since Added in version 3.0. - * - * @ingroup context - */ -GLFWAPI GLFWwindow *glfwGetCurrentContext(void); - -/*! @brief Swaps the front and back buffers of the specified window. - * - * This function swaps the front and back buffers of the specified window when - * rendering with OpenGL or OpenGL ES. If the swap interval is greater than - * zero, the GPU driver waits the specified number of screen updates before - * swapping the buffers. - * - * The specified window must have an OpenGL or OpenGL ES context. Specifying - * a window without a context will generate a @ref GLFW_NO_WINDOW_CONTEXT - * error. - * - * This function does not apply to Vulkan. If you are rendering with Vulkan, - * see `vkQueuePresentKHR` instead. - * - * @param[in] window The window whose buffers to swap. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_NO_WINDOW_CONTEXT and @ref GLFW_PLATFORM_ERROR. - * - * @remark __EGL:__ The context of the specified window must be current on the - * calling thread. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref buffer_swap - * @sa @ref glfwSwapInterval - * - * @since Added in version 1.0. - * @glfw3 Added window handle parameter. - * - * @ingroup window - */ -GLFWAPI void glfwSwapBuffers(GLFWwindow *window); - -/*! @brief Sets the swap interval for the current context. - * - * This function sets the swap interval for the current OpenGL or OpenGL ES - * context, i.e. the number of screen updates to wait from the time @ref - * glfwSwapBuffers was called before swapping the buffers and returning. This - * is sometimes called _vertical synchronization_, _vertical retrace - * synchronization_ or just _vsync_. - * - * A context that supports either of the `WGL_EXT_swap_control_tear` and - * `GLX_EXT_swap_control_tear` extensions also accepts _negative_ swap - * intervals, which allows the driver to swap immediately even if a frame - * arrives a little bit late. You can check for these extensions with @ref - * glfwExtensionSupported. - * - * A context must be current on the calling thread. Calling this function - * without a current context will cause a @ref GLFW_NO_CURRENT_CONTEXT error. - * - * This function does not apply to Vulkan. If you are rendering with Vulkan, - * see the present mode of your swapchain instead. - * - * @param[in] interval The minimum number of screen updates to wait for - * until the buffers are swapped by @ref glfwSwapBuffers. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_NO_CURRENT_CONTEXT and @ref GLFW_PLATFORM_ERROR. - * - * @remark This function is not called during context creation, leaving the - * swap interval set to whatever is the default on that platform. This is done - * because some swap interval extensions used by GLFW do not allow the swap - * interval to be reset to zero once it has been set to a non-zero value. - * - * @remark Some GPU drivers do not honor the requested swap interval, either - * because of a user setting that overrides the application's request or due to - * bugs in the driver. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref buffer_swap - * @sa @ref glfwSwapBuffers - * - * @since Added in version 1.0. - * - * @ingroup context - */ -GLFWAPI void glfwSwapInterval(int interval); - -/*! @brief Returns whether the specified extension is available. - * - * This function returns whether the specified - * [API extension](@ref context_glext) is supported by the current OpenGL or - * OpenGL ES context. It searches both for client API extension and context - * creation API extensions. - * - * A context must be current on the calling thread. Calling this function - * without a current context will cause a @ref GLFW_NO_CURRENT_CONTEXT error. - * - * As this functions retrieves and searches one or more extension strings each - * call, it is recommended that you cache its results if it is going to be used - * frequently. The extension strings will not change during the lifetime of - * a context, so there is no danger in doing this. - * - * This function does not apply to Vulkan. If you are using Vulkan, see @ref - * glfwGetRequiredInstanceExtensions, `vkEnumerateInstanceExtensionProperties` - * and `vkEnumerateDeviceExtensionProperties` instead. - * - * @param[in] extension The ASCII encoded name of the extension. - * @return `true` if the extension is available, or `false` - * otherwise. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_NO_CURRENT_CONTEXT, @ref GLFW_INVALID_VALUE and @ref - * GLFW_PLATFORM_ERROR. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref context_glext - * @sa @ref glfwGetProcAddress - * - * @since Added in version 1.0. - * - * @ingroup context - */ -GLFWAPI int glfwExtensionSupported(const char *extension); - -/*! @brief Returns the address of the specified function for the current - * context. - * - * This function returns the address of the specified OpenGL or OpenGL ES - * [core or extension function](@ref context_glext), if it is supported - * by the current context. - * - * A context must be current on the calling thread. Calling this function - * without a current context will cause a @ref GLFW_NO_CURRENT_CONTEXT error. - * - * This function does not apply to Vulkan. If you are rendering with Vulkan, - * see @ref glfwGetInstanceProcAddress, `vkGetInstanceProcAddr` and - * `vkGetDeviceProcAddr` instead. - * - * @param[in] procname The ASCII encoded name of the function. - * @return The address of the function, or `NULL` if an - * [error](@ref error_handling) occurred. - * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_NO_CURRENT_CONTEXT and @ref GLFW_PLATFORM_ERROR. - * - * @remark The address of a given function is not guaranteed to be the same - * between contexts. - * - * @remark This function may return a non-`NULL` address despite the - * associated version or extension not being available. Always check the - * context version or extension string first. - * - * @pointer_lifetime The returned function pointer is valid until the context - * is destroyed or the library is terminated. - * - * @thread_safety This function may be called from any thread. - * - * @sa @ref context_glext - * @sa @ref glfwExtensionSupported - * - * @since Added in version 1.0. - * - * @ingroup context - */ -GLFWAPI GLFWglproc glfwGetProcAddress(const char *procname); - /*! @brief Returns whether the Vulkan loader and an ICD have been found. * * This function returns whether the Vulkan loader and any minimally functional diff --git a/glfw/glx_context.c b/glfw/glx_context.c deleted file mode 100644 index 9f414e2d4..000000000 --- a/glfw/glx_context.c +++ /dev/null @@ -1,549 +0,0 @@ -//======================================================================== -// GLFW 3.4 GLX - www.glfw.org -//------------------------------------------------------------------------ -// Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2019 Camilla Löwy -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would -// be appreciated but is not required. -// -// 2. Altered source versions must be plainly marked as such, and must not -// be misrepresented as being the original software. -// -// 3. This notice may not be removed or altered from any source -// distribution. -// -//======================================================================== -// It is fine to use C99 in this file because it will not be built with VS -//======================================================================== - -#include "internal.h" - -#include -#include -#include - -#ifndef GLXBadProfileARB -#define GLXBadProfileARB 13 -#endif - - -// Returns the specified attribute of the specified GLXFBConfig -// -static int -getGLXFBConfigAttrib(GLXFBConfig fbconfig, int attrib) { - int value; - glXGetFBConfigAttrib(_glfw.x11.display, fbconfig, attrib, &value); - return value; -} - -static GLXFBConfig * -choose_fb_config(const _GLFWfbconfig *desired, bool trust_window_bit, int *nelements, bool use_best_color_depth) { - int attrib_list[64]; - int pos = 0; -#define ATTR(x, y) \ - { \ - attrib_list[pos++] = x; \ - attrib_list[pos++] = y; \ - } - - ATTR(GLX_DOUBLEBUFFER, desired->doublebuffer ? True : False); - if (desired->stereo > 0) ATTR(GLX_STEREO, desired->stereo ? True : False); - if (desired->auxBuffers > 0) ATTR(GLX_AUX_BUFFERS, desired->auxBuffers); - if (_glfw.glx.ARB_multisample && desired->samples > 0) ATTR(GLX_SAMPLES, desired->samples); - if (desired->depthBits != GLFW_DONT_CARE) ATTR(GLX_DEPTH_SIZE, desired->depthBits); - if (desired->stencilBits != GLFW_DONT_CARE) ATTR(GLX_STENCIL_SIZE, desired->stencilBits); - if (use_best_color_depth) { - // we just ask for the highest available R+G+B+A color depth. This hopefully - // works with 10bit (r=10, g=10, b=19, a=2) visuals - ATTR(GLX_RED_SIZE, 1); - ATTR(GLX_GREEN_SIZE, 1); - ATTR(GLX_BLUE_SIZE, 1); - ATTR(GLX_ALPHA_SIZE, 1); - } else { - if (desired->redBits != GLFW_DONT_CARE) ATTR(GLX_RED_SIZE, desired->redBits); - if (desired->greenBits != GLFW_DONT_CARE) ATTR(GLX_GREEN_SIZE, desired->greenBits); - if (desired->blueBits != GLFW_DONT_CARE) ATTR(GLX_BLUE_SIZE, desired->blueBits); - if (desired->alphaBits != GLFW_DONT_CARE) ATTR(GLX_ALPHA_SIZE, desired->alphaBits); - } - if (desired->accumRedBits != GLFW_DONT_CARE) ATTR(GLX_ACCUM_RED_SIZE, desired->accumRedBits); - if (desired->accumGreenBits != GLFW_DONT_CARE) ATTR(GLX_ACCUM_GREEN_SIZE, desired->accumGreenBits); - if (desired->accumBlueBits != GLFW_DONT_CARE) ATTR(GLX_ACCUM_BLUE_SIZE, desired->accumBlueBits); - if (desired->accumAlphaBits != GLFW_DONT_CARE) ATTR(GLX_ACCUM_ALPHA_SIZE, desired->accumAlphaBits); - if (!trust_window_bit) ATTR(GLX_DRAWABLE_TYPE, 0); - ATTR(None, None); - return glXChooseFBConfig(_glfw.x11.display, _glfw.x11.screen, attrib_list, nelements); -#undef ATTR -} - - -// Return the GLXFBConfig most closely matching the specified hints -// -static bool -chooseGLXFBConfig(const _GLFWfbconfig *desired, GLXFBConfig *result) { - GLXFBConfig *nativeConfigs; - int i, nativeCount, ans_idx = 0; - const char *vendor; - bool trustWindowBit = true; - static _GLFWfbconfig prev_desired = {0}; - static GLXFBConfig prev_result = 0; - if (prev_result != 0 && memcmp(&prev_desired, desired, sizeof(_GLFWfbconfig)) == 0) { - *result = prev_result; - return true; - } - prev_desired = *desired; - - // HACK: This is a (hopefully temporary) workaround for Chromium - // (VirtualBox GL) not setting the window bit on any GLXFBConfigs - vendor = glXGetClientString(_glfw.x11.display, GLX_VENDOR); - if (vendor && strcmp(vendor, "Chromium") == 0) trustWindowBit = false; - nativeConfigs = choose_fb_config(desired, trustWindowBit, &nativeCount, false); - if (!nativeConfigs || !nativeCount) { - nativeConfigs = choose_fb_config(desired, trustWindowBit, &nativeCount, true); - - if (!nativeConfigs || !nativeCount) { - _glfwInputError(GLFW_API_UNAVAILABLE, "GLX: No GLXFBConfigs returned"); - return false; - } - } - for (i = 0; i < nativeCount; i++) { - const GLXFBConfig n = nativeConfigs[i]; - bool transparency_matches = true, srgb_matches = true; - if (desired->transparent) { - transparency_matches = false; - XVisualInfo *vi = glXGetVisualFromFBConfig(_glfw.x11.display, n); - if (vi && _glfwIsVisualTransparentX11(vi->visual)) transparency_matches = true; - } - - if (desired->sRGB && (_glfw.glx.ARB_framebuffer_sRGB || _glfw.glx.EXT_framebuffer_sRGB)) { - srgb_matches = getGLXFBConfigAttrib(n, GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB) ? true : false; - } - - if (transparency_matches && srgb_matches) { - ans_idx = i; - break; - } - } - - *result = nativeConfigs[ans_idx]; - prev_result = nativeConfigs[ans_idx]; - - XFree(nativeConfigs); - - return true; -} - -// Create the OpenGL context using legacy API -// -static GLXContext -createLegacyContextGLX(_GLFWwindow *window UNUSED, GLXFBConfig fbconfig, GLXContext share) { - return glXCreateNewContext(_glfw.x11.display, fbconfig, GLX_RGBA_TYPE, share, True); -} - -static void -makeContextCurrentGLX(_GLFWwindow *window) { - if (window) { - if (!glXMakeCurrent(_glfw.x11.display, window->context.glx.window, window->context.glx.handle)) { - _glfwInputError(GLFW_PLATFORM_ERROR, "GLX: Failed to make context current"); - return; - } - } else { - if (!glXMakeCurrent(_glfw.x11.display, None, NULL)) { - _glfwInputError(GLFW_PLATFORM_ERROR, "GLX: Failed to clear current context"); - return; - } - } - - _glfwPlatformSetTls(&_glfw.contextSlot, window); -} - -static void -swapBuffersGLX(_GLFWwindow *window) { - glXSwapBuffers(_glfw.x11.display, window->context.glx.window); -} - -static void -swapIntervalGLX(int interval) { - _GLFWwindow *window = _glfwPlatformGetTls(&_glfw.contextSlot); - - if (_glfw.glx.EXT_swap_control) { - _glfw.glx.SwapIntervalEXT(_glfw.x11.display, window->context.glx.window, interval); - } else if (_glfw.glx.MESA_swap_control) _glfw.glx.SwapIntervalMESA(interval); - else if (_glfw.glx.SGI_swap_control) { - if (interval > 0) _glfw.glx.SwapIntervalSGI(interval); - } -} - -static int -extensionSupportedGLX(const char *extension) { - const char *extensions = glXQueryExtensionsString(_glfw.x11.display, _glfw.x11.screen); - if (extensions) { - if (_glfwStringInExtensionString(extension, extensions)) return true; - } - - return false; -} - -static GLFWglproc -getProcAddressGLX(const char *procname) { - if (_glfw.glx.GetProcAddress) return _glfw.glx.GetProcAddress((const GLubyte *)procname); - else if (_glfw.glx.GetProcAddressARB) return _glfw.glx.GetProcAddressARB((const GLubyte *)procname); - else { - GLFWglproc ans = NULL; - glfw_dlsym(ans, _glfw.glx.handle, procname); - return ans; - } -} - -static void -destroyContextGLX(_GLFWwindow *window) { - if (window->context.glx.window) { - glXDestroyWindow(_glfw.x11.display, window->context.glx.window); - window->context.glx.window = None; - } - - if (window->context.glx.handle) { - glXDestroyContext(_glfw.x11.display, window->context.glx.handle); - window->context.glx.handle = NULL; - } -} - - -////////////////////////////////////////////////////////////////////////// -////// GLFW internal API ////// -////////////////////////////////////////////////////////////////////////// - -// Initialize GLX -// -bool -_glfwInitGLX(void) { - int i; - const char *sonames[] = { -#if defined(_GLFW_GLX_LIBRARY) - _GLFW_GLX_LIBRARY, -#elif defined(__CYGWIN__) - "libGL-1.so", -#else - "libGL.so.1", - "libGL.so", -#endif - NULL}; - - if (_glfw.glx.handle) return true; - - for (i = 0; sonames[i]; i++) { - _glfw.glx.handle = _glfw_dlopen(sonames[i]); - if (_glfw.glx.handle) break; - } - - if (!_glfw.glx.handle) { - _glfwInputError(GLFW_API_UNAVAILABLE, "GLX: Failed to load GLX"); - return false; - } - - glfw_dlsym(_glfw.glx.GetFBConfigs, _glfw.glx.handle, "glXGetFBConfigs"); - glfw_dlsym(_glfw.glx.GetFBConfigAttrib, _glfw.glx.handle, "glXGetFBConfigAttrib"); - glfw_dlsym(_glfw.glx.ChooseFBConfig, _glfw.glx.handle, "glXChooseFBConfig"); - glfw_dlsym(_glfw.glx.GetClientString, _glfw.glx.handle, "glXGetClientString"); - glfw_dlsym(_glfw.glx.QueryExtension, _glfw.glx.handle, "glXQueryExtension"); - glfw_dlsym(_glfw.glx.QueryVersion, _glfw.glx.handle, "glXQueryVersion"); - glfw_dlsym(_glfw.glx.DestroyContext, _glfw.glx.handle, "glXDestroyContext"); - glfw_dlsym(_glfw.glx.MakeCurrent, _glfw.glx.handle, "glXMakeCurrent"); - glfw_dlsym(_glfw.glx.SwapBuffers, _glfw.glx.handle, "glXSwapBuffers"); - glfw_dlsym(_glfw.glx.QueryExtensionsString, _glfw.glx.handle, "glXQueryExtensionsString"); - glfw_dlsym(_glfw.glx.CreateNewContext, _glfw.glx.handle, "glXCreateNewContext"); - glfw_dlsym(_glfw.glx.CreateWindow, _glfw.glx.handle, "glXCreateWindow"); - glfw_dlsym(_glfw.glx.DestroyWindow, _glfw.glx.handle, "glXDestroyWindow"); - glfw_dlsym(_glfw.glx.GetProcAddress, _glfw.glx.handle, "glXGetProcAddress"); - glfw_dlsym(_glfw.glx.GetProcAddressARB, _glfw.glx.handle, "glXGetProcAddressARB"); - glfw_dlsym(_glfw.glx.GetVisualFromFBConfig, _glfw.glx.handle, "glXGetVisualFromFBConfig"); - - if (!_glfw.glx.GetFBConfigs || !_glfw.glx.GetFBConfigAttrib || !_glfw.glx.GetClientString || !_glfw.glx.QueryExtension || !_glfw.glx.QueryVersion || - !_glfw.glx.DestroyContext || !_glfw.glx.MakeCurrent || !_glfw.glx.SwapBuffers || !_glfw.glx.QueryExtensionsString || !_glfw.glx.CreateNewContext || - !_glfw.glx.CreateWindow || !_glfw.glx.DestroyWindow || !_glfw.glx.GetProcAddress || !_glfw.glx.GetProcAddressARB || !_glfw.glx.GetVisualFromFBConfig) { - _glfwInputError(GLFW_PLATFORM_ERROR, "GLX: Failed to load required entry points"); - return false; - } - - if (!glXQueryExtension(_glfw.x11.display, &_glfw.glx.errorBase, &_glfw.glx.eventBase)) { - _glfwInputError(GLFW_API_UNAVAILABLE, "GLX: GLX extension not found"); - return false; - } - - if (!glXQueryVersion(_glfw.x11.display, &_glfw.glx.major, &_glfw.glx.minor)) { - _glfwInputError(GLFW_API_UNAVAILABLE, "GLX: Failed to query GLX version"); - return false; - } - - if (_glfw.glx.major == 1 && _glfw.glx.minor < 3) { - _glfwInputError(GLFW_API_UNAVAILABLE, "GLX: GLX version 1.3 is required"); - return false; - } - - if (extensionSupportedGLX("GLX_EXT_swap_control")) { - _glfw.glx.SwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)getProcAddressGLX("glXSwapIntervalEXT"); - - if (_glfw.glx.SwapIntervalEXT) _glfw.glx.EXT_swap_control = true; - } - - if (extensionSupportedGLX("GLX_SGI_swap_control")) { - _glfw.glx.SwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC)getProcAddressGLX("glXSwapIntervalSGI"); - - if (_glfw.glx.SwapIntervalSGI) _glfw.glx.SGI_swap_control = true; - } - - if (extensionSupportedGLX("GLX_MESA_swap_control")) { - _glfw.glx.SwapIntervalMESA = (PFNGLXSWAPINTERVALMESAPROC)getProcAddressGLX("glXSwapIntervalMESA"); - - if (_glfw.glx.SwapIntervalMESA) _glfw.glx.MESA_swap_control = true; - } - - if (extensionSupportedGLX("GLX_ARB_multisample")) _glfw.glx.ARB_multisample = true; - - if (extensionSupportedGLX("GLX_ARB_framebuffer_sRGB")) _glfw.glx.ARB_framebuffer_sRGB = true; - - if (extensionSupportedGLX("GLX_EXT_framebuffer_sRGB")) _glfw.glx.EXT_framebuffer_sRGB = true; - - if (extensionSupportedGLX("GLX_ARB_create_context")) { - _glfw.glx.CreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC)getProcAddressGLX("glXCreateContextAttribsARB"); - - if (_glfw.glx.CreateContextAttribsARB) _glfw.glx.ARB_create_context = true; - } - - if (extensionSupportedGLX("GLX_ARB_create_context_robustness")) _glfw.glx.ARB_create_context_robustness = true; - - if (extensionSupportedGLX("GLX_ARB_create_context_profile")) _glfw.glx.ARB_create_context_profile = true; - - if (extensionSupportedGLX("GLX_EXT_create_context_es2_profile")) _glfw.glx.EXT_create_context_es2_profile = true; - - if (extensionSupportedGLX("GLX_ARB_create_context_no_error")) _glfw.glx.ARB_create_context_no_error = true; - - if (extensionSupportedGLX("GLX_ARB_context_flush_control")) _glfw.glx.ARB_context_flush_control = true; - - return true; -} - -// Terminate GLX -// -void -_glfwTerminateGLX(void) { - // NOTE: This function must not call any X11 functions, as it is called - // after XCloseDisplay (see _glfwPlatformTerminate for details) - - if (_glfw.glx.handle) { - _glfw_dlclose(_glfw.glx.handle); - _glfw.glx.handle = NULL; - } -} - -#define setAttrib(a, v) \ - { \ - assert(((size_t)index + 1) < sizeof(attribs) / sizeof(attribs[0])); \ - attribs[index++] = a; \ - attribs[index++] = v; \ - } - -// Create the OpenGL or OpenGL ES context -// -bool -_glfwCreateContextGLX(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig) { - int attribs[40]; - int x_error = Success; - GLXFBConfig native = NULL; - GLXContext share = NULL; - - if (ctxconfig->share) share = ctxconfig->share->context.glx.handle; - - if (!chooseGLXFBConfig(fbconfig, &native)) { - _glfwInputError(GLFW_FORMAT_UNAVAILABLE, "GLX: Failed to find a suitable GLXFBConfig"); - return false; - } - - if (ctxconfig->client == GLFW_OPENGL_ES_API) { - if (!_glfw.glx.ARB_create_context || !_glfw.glx.ARB_create_context_profile || !_glfw.glx.EXT_create_context_es2_profile) { - _glfwInputError(GLFW_API_UNAVAILABLE, "GLX: OpenGL ES requested but GLX_EXT_create_context_es2_profile is unavailable"); - return false; - } - } - - if (ctxconfig->forward) { - if (!_glfw.glx.ARB_create_context) { - _glfwInputError(GLFW_VERSION_UNAVAILABLE, "GLX: Forward compatibility requested but GLX_ARB_create_context_profile is unavailable"); - return false; - } - } - - if (ctxconfig->profile) { - if (!_glfw.glx.ARB_create_context || !_glfw.glx.ARB_create_context_profile) { - _glfwInputError(GLFW_VERSION_UNAVAILABLE, "GLX: An OpenGL profile requested but GLX_ARB_create_context_profile is unavailable"); - return false; - } - } - - _glfwPushErrorTrapX11(); - - if (_glfw.glx.ARB_create_context) { - int index = 0, mask = 0, flags = 0; - - if (ctxconfig->client == GLFW_OPENGL_API) { - if (ctxconfig->forward) flags |= GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; - - if (ctxconfig->profile == GLFW_OPENGL_CORE_PROFILE) mask |= GLX_CONTEXT_CORE_PROFILE_BIT_ARB; - else if (ctxconfig->profile == GLFW_OPENGL_COMPAT_PROFILE) mask |= GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; - } else mask |= GLX_CONTEXT_ES2_PROFILE_BIT_EXT; - - if (ctxconfig->debug) flags |= GLX_CONTEXT_DEBUG_BIT_ARB; - - if (ctxconfig->robustness) { - if (_glfw.glx.ARB_create_context_robustness) { - if (ctxconfig->robustness == GLFW_NO_RESET_NOTIFICATION) { - setAttrib(GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB, GLX_NO_RESET_NOTIFICATION_ARB); - } else if (ctxconfig->robustness == GLFW_LOSE_CONTEXT_ON_RESET) { - setAttrib(GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB, GLX_LOSE_CONTEXT_ON_RESET_ARB); - } - - flags |= GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB; - } - } - - if (ctxconfig->release) { - if (_glfw.glx.ARB_context_flush_control) { - if (ctxconfig->release == GLFW_RELEASE_BEHAVIOR_NONE) { - setAttrib(GLX_CONTEXT_RELEASE_BEHAVIOR_ARB, GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB); - } else if (ctxconfig->release == GLFW_RELEASE_BEHAVIOR_FLUSH) { - setAttrib(GLX_CONTEXT_RELEASE_BEHAVIOR_ARB, GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB); - } - } - } - - if (ctxconfig->noerror) { - if (_glfw.glx.ARB_create_context_no_error) setAttrib(GLX_CONTEXT_OPENGL_NO_ERROR_ARB, true); - } - - // NOTE: Only request an explicitly versioned context when necessary, as - // explicitly requesting version 1.0 does not always return the - // highest version supported by the driver - if (ctxconfig->major != 1 || ctxconfig->minor != 0) { - setAttrib(GLX_CONTEXT_MAJOR_VERSION_ARB, ctxconfig->major); - setAttrib(GLX_CONTEXT_MINOR_VERSION_ARB, ctxconfig->minor); - } - - if (mask) setAttrib(GLX_CONTEXT_PROFILE_MASK_ARB, mask); - - if (flags) setAttrib(GLX_CONTEXT_FLAGS_ARB, flags); - - setAttrib(None, None); - - window->context.glx.handle = _glfw.glx.CreateContextAttribsARB(_glfw.x11.display, native, share, True, attribs); - x_error = _glfwPopErrorTrapX11(); - - // HACK: This is a fallback for broken versions of the Mesa - // implementation of GLX_ARB_create_context_profile that fail - // default 1.0 context creation with a GLXBadProfileARB error in - // violation of the extension spec - if (!window->context.glx.handle) { - if (x_error == _glfw.glx.errorBase + GLXBadProfileARB && ctxconfig->client == GLFW_OPENGL_API && ctxconfig->profile == GLFW_OPENGL_ANY_PROFILE && - ctxconfig->forward == false) { - _glfwPushErrorTrapX11(); - window->context.glx.handle = createLegacyContextGLX(window, native, share); - x_error = _glfwPopErrorTrapX11(); - } - } - } else { - window->context.glx.handle = createLegacyContextGLX(window, native, share); - x_error = _glfwPopErrorTrapX11(); - } - - if (!window->context.glx.handle) { - _glfwInputErrorX11(GLFW_VERSION_UNAVAILABLE, x_error, "GLX: Failed to create context"); - return false; - } - - window->context.glx.window = glXCreateWindow(_glfw.x11.display, native, window->x11.handle, NULL); - if (!window->context.glx.window) { - _glfwInputError(GLFW_PLATFORM_ERROR, "GLX: Failed to create window"); - return false; - } - - window->context.makeCurrent = makeContextCurrentGLX; - window->context.swapBuffers = swapBuffersGLX; - window->context.swapInterval = swapIntervalGLX; - window->context.extensionSupported = extensionSupportedGLX; - window->context.getProcAddress = getProcAddressGLX; - window->context.destroy = destroyContextGLX; - - return true; -} - -#undef setAttrib - -// Returns the Visual and depth of the chosen GLXFBConfig -// -bool -_glfwChooseVisualGLX( - const _GLFWwndconfig *wndconfig UNUSED, const _GLFWctxconfig *ctxconfig UNUSED, const _GLFWfbconfig *fbconfig, Visual **visual, int *depth) { - GLXFBConfig native; - XVisualInfo *result; - - if (!chooseGLXFBConfig(fbconfig, &native)) { - _glfwInputError(GLFW_FORMAT_UNAVAILABLE, "GLX: Failed to find a suitable GLXFBConfig"); - return false; - } - - result = glXGetVisualFromFBConfig(_glfw.x11.display, native); - if (!result) { - _glfwInputError(GLFW_PLATFORM_ERROR, "GLX: Failed to retrieve Visual for GLXFBConfig"); - return false; - } - - *visual = result->visual; - *depth = result->depth; - - XFree(result); - return true; -} - - -////////////////////////////////////////////////////////////////////////// -////// GLFW native API ////// -////////////////////////////////////////////////////////////////////////// - -GLFWAPI GLXContext -glfwGetGLXContext(GLFWwindow *handle) { - _GLFWwindow *window = (_GLFWwindow *)handle; - assert(window != NULL); - - _GLFW_REQUIRE_INIT_OR_RETURN(NULL); - - if (window->context.client == GLFW_NO_API) { - _glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL); - return NULL; - } - - return window->context.glx.handle; -} - -GLFWAPI GLXWindow -glfwGetGLXWindow(GLFWwindow *handle) { - _GLFWwindow *window = (_GLFWwindow *)handle; - assert(window != NULL); - - _GLFW_REQUIRE_INIT_OR_RETURN(None); - - if (window->context.client == GLFW_NO_API) { - _glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL); - return None; - } - - return window->context.glx.window; -} diff --git a/glfw/glx_context.h b/glfw/glx_context.h deleted file mode 100644 index 325093829..000000000 --- a/glfw/glx_context.h +++ /dev/null @@ -1,176 +0,0 @@ -//======================================================================== -// GLFW 3.4 GLX - www.glfw.org -//------------------------------------------------------------------------ -// Copyright (c) 2002-2006 Marcus Geelnard -// Copyright (c) 2006-2017 Camilla Löwy -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would -// be appreciated but is not required. -// -// 2. Altered source versions must be plainly marked as such, and must not -// be misrepresented as being the original software. -// -// 3. This notice may not be removed or altered from any source -// distribution. -// -//======================================================================== - -#define GLX_VENDOR 1 -#define GLX_RGBA_BIT 0x00000001 -#define GLX_WINDOW_BIT 0x00000001 -#define GLX_DRAWABLE_TYPE 0x8010 -#define GLX_RENDER_TYPE 0x8011 -#define GLX_RGBA_TYPE 0x8014 -#define GLX_DOUBLEBUFFER 5 -#define GLX_STEREO 6 -#define GLX_AUX_BUFFERS 7 -#define GLX_RED_SIZE 8 -#define GLX_GREEN_SIZE 9 -#define GLX_BLUE_SIZE 10 -#define GLX_ALPHA_SIZE 11 -#define GLX_DEPTH_SIZE 12 -#define GLX_STENCIL_SIZE 13 -#define GLX_ACCUM_RED_SIZE 14 -#define GLX_ACCUM_GREEN_SIZE 15 -#define GLX_ACCUM_BLUE_SIZE 16 -#define GLX_ACCUM_ALPHA_SIZE 17 -#define GLX_SAMPLES 0x186a1 -#define GLX_VISUAL_ID 0x800b - -#define GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20b2 -#define GLX_CONTEXT_DEBUG_BIT_ARB 0x00000001 -#define GLX_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB 0x00000002 -#define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001 -#define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126 -#define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002 -#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 -#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 -#define GLX_CONTEXT_FLAGS_ARB 0x2094 -#define GLX_CONTEXT_ES2_PROFILE_BIT_EXT 0x00000004 -#define GLX_CONTEXT_ROBUST_ACCESS_BIT_ARB 0x00000004 -#define GLX_LOSE_CONTEXT_ON_RESET_ARB 0x8252 -#define GLX_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB 0x8256 -#define GLX_NO_RESET_NOTIFICATION_ARB 0x8261 -#define GLX_CONTEXT_RELEASE_BEHAVIOR_ARB 0x2097 -#define GLX_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB 0 -#define GLX_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB 0x2098 -#define GLX_CONTEXT_OPENGL_NO_ERROR_ARB 0x31b3 - -typedef XID GLXWindow; -typedef XID GLXDrawable; -typedef struct __GLXFBConfig *GLXFBConfig; -typedef struct __GLXcontext *GLXContext; -typedef void (*__GLXextproc)(void); - -typedef int (*PFNGLXGETFBCONFIGATTRIBPROC)(Display *, GLXFBConfig, int, int *); -typedef GLXFBConfig *(*PFNGLXCHOOSEFBCONFIGPROC)(Display *, int, const int *, int *); -typedef const char *(*PFNGLXGETCLIENTSTRINGPROC)(Display *, int); -typedef Bool (*PFNGLXQUERYEXTENSIONPROC)(Display *, int *, int *); -typedef Bool (*PFNGLXQUERYVERSIONPROC)(Display *, int *, int *); -typedef void (*PFNGLXDESTROYCONTEXTPROC)(Display *, GLXContext); -typedef Bool (*PFNGLXMAKECURRENTPROC)(Display *, GLXDrawable, GLXContext); -typedef void (*PFNGLXSWAPBUFFERSPROC)(Display *, GLXDrawable); -typedef const char *(*PFNGLXQUERYEXTENSIONSSTRINGPROC)(Display *, int); -typedef GLXFBConfig *(*PFNGLXGETFBCONFIGSPROC)(Display *, int, int *); -typedef GLXContext (*PFNGLXCREATENEWCONTEXTPROC)(Display *, GLXFBConfig, int, GLXContext, Bool); -typedef __GLXextproc (*PFNGLXGETPROCADDRESSPROC)(const GLubyte *procName); -typedef void (*PFNGLXSWAPINTERVALEXTPROC)(Display *, GLXDrawable, int); -typedef XVisualInfo *(*PFNGLXGETVISUALFROMFBCONFIGPROC)(Display *, GLXFBConfig); -typedef GLXWindow (*PFNGLXCREATEWINDOWPROC)(Display *, GLXFBConfig, Window, const int *); -typedef void (*PFNGLXDESTROYWINDOWPROC)(Display *, GLXWindow); - -typedef int (*PFNGLXSWAPINTERVALMESAPROC)(int); -typedef int (*PFNGLXSWAPINTERVALSGIPROC)(int); -typedef GLXContext (*PFNGLXCREATECONTEXTATTRIBSARBPROC)(Display *, GLXFBConfig, GLXContext, Bool, const int *); - -// libGL.so function pointer typedefs -#define glXGetFBConfigs _glfw.glx.GetFBConfigs -#define glXGetFBConfigAttrib _glfw.glx.GetFBConfigAttrib -#define glXChooseFBConfig _glfw.glx.ChooseFBConfig -#define glXGetClientString _glfw.glx.GetClientString -#define glXQueryExtension _glfw.glx.QueryExtension -#define glXQueryVersion _glfw.glx.QueryVersion -#define glXDestroyContext _glfw.glx.DestroyContext -#define glXMakeCurrent _glfw.glx.MakeCurrent -#define glXSwapBuffers _glfw.glx.SwapBuffers -#define glXQueryExtensionsString _glfw.glx.QueryExtensionsString -#define glXCreateNewContext _glfw.glx.CreateNewContext -#define glXGetVisualFromFBConfig _glfw.glx.GetVisualFromFBConfig -#define glXCreateWindow _glfw.glx.CreateWindow -#define glXDestroyWindow _glfw.glx.DestroyWindow - -#define _GLFW_PLATFORM_CONTEXT_STATE _GLFWcontextGLX glx; -#define _GLFW_PLATFORM_LIBRARY_CONTEXT_STATE _GLFWlibraryGLX glx; - - -// GLX-specific per-context data -// -typedef struct _GLFWcontextGLX { - GLXContext handle; - GLXWindow window; - -} _GLFWcontextGLX; - -// GLX-specific global data -// -typedef struct _GLFWlibraryGLX { - int major, minor; - int eventBase; - int errorBase; - - // dlopen handle for libGL.so.1 - void *handle; - - // GLX 1.3 functions - PFNGLXGETFBCONFIGSPROC GetFBConfigs; - PFNGLXGETFBCONFIGATTRIBPROC GetFBConfigAttrib; - PFNGLXCHOOSEFBCONFIGPROC ChooseFBConfig; - PFNGLXGETCLIENTSTRINGPROC GetClientString; - PFNGLXQUERYEXTENSIONPROC QueryExtension; - PFNGLXQUERYVERSIONPROC QueryVersion; - PFNGLXDESTROYCONTEXTPROC DestroyContext; - PFNGLXMAKECURRENTPROC MakeCurrent; - PFNGLXSWAPBUFFERSPROC SwapBuffers; - PFNGLXQUERYEXTENSIONSSTRINGPROC QueryExtensionsString; - PFNGLXCREATENEWCONTEXTPROC CreateNewContext; - PFNGLXGETVISUALFROMFBCONFIGPROC GetVisualFromFBConfig; - PFNGLXCREATEWINDOWPROC CreateWindow; - PFNGLXDESTROYWINDOWPROC DestroyWindow; - - // GLX 1.4 and extension functions - PFNGLXGETPROCADDRESSPROC GetProcAddress; - PFNGLXGETPROCADDRESSPROC GetProcAddressARB; - PFNGLXSWAPINTERVALSGIPROC SwapIntervalSGI; - PFNGLXSWAPINTERVALEXTPROC SwapIntervalEXT; - PFNGLXSWAPINTERVALMESAPROC SwapIntervalMESA; - PFNGLXCREATECONTEXTATTRIBSARBPROC CreateContextAttribsARB; - bool SGI_swap_control; - bool EXT_swap_control; - bool MESA_swap_control; - bool ARB_multisample; - bool ARB_framebuffer_sRGB; - bool EXT_framebuffer_sRGB; - bool ARB_create_context; - bool ARB_create_context_profile; - bool ARB_create_context_robustness; - bool EXT_create_context_es2_profile; - bool ARB_create_context_no_error; - bool ARB_context_flush_control; - -} _GLFWlibraryGLX; - -bool _glfwInitGLX(void); -void _glfwTerminateGLX(void); -bool _glfwCreateContextGLX(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig); -void _glfwDestroyContextGLX(_GLFWwindow *window); -bool _glfwChooseVisualGLX(const _GLFWwndconfig *wndconfig, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig, Visual **visual, int *depth); diff --git a/glfw/init.c b/glfw/init.c index 31c93e468..9e8e42376 100644 --- a/glfw/init.c +++ b/glfw/init.c @@ -51,7 +51,6 @@ static _GLFWerror _glfwMainThreadError; static GLFWerrorfun _glfwErrorCallback; static _GLFWinitconfig _glfwInitHints = { .hatButtons = true, - .angleType = GLFW_ANGLE_PLATFORM_TYPE_NONE, .debugKeyboard = false, .debugRendering = false, .ns = @@ -105,7 +104,6 @@ terminate(void) { free(error); } - _glfwPlatformDestroyTls(&_glfw.contextSlot); _glfwPlatformDestroyTls(&_glfw.errorSlot); _glfwPlatformDestroyMutex(&_glfw.errorLock); @@ -148,7 +146,6 @@ _glfwInputError(int code, const char *format, ...) { description[sizeof(description) - 1] = '\0'; } else { if (code == GLFW_NOT_INITIALIZED) strcpy(description, "The GLFW library is not initialized"); - else if (code == GLFW_NO_CURRENT_CONTEXT) strcpy(description, "There is no current context"); else if (code == GLFW_INVALID_ENUM) strcpy(description, "Invalid argument for enum parameter"); else if (code == GLFW_INVALID_VALUE) strcpy(description, "Invalid value for parameter"); else if (code == GLFW_OUT_OF_MEMORY) strcpy(description, "Out of memory"); @@ -156,7 +153,6 @@ _glfwInputError(int code, const char *format, ...) { else if (code == GLFW_VERSION_UNAVAILABLE) strcpy(description, "The requested API version is unavailable"); else if (code == GLFW_PLATFORM_ERROR) strcpy(description, "A platform-specific error occurred"); else if (code == GLFW_FORMAT_UNAVAILABLE) strcpy(description, "The requested format is unavailable"); - else if (code == GLFW_NO_WINDOW_CONTEXT) strcpy(description, "The specified window has no context"); else if (code == GLFW_FEATURE_UNAVAILABLE) strcpy(description, "The requested feature cannot be implemented for this platform"); else if (code == GLFW_FEATURE_UNIMPLEMENTED) strcpy(description, "The requested feature has not yet been implemented for this platform"); else strcpy(description, "ERROR: UNKNOWN GLFW ERROR"); @@ -212,7 +208,7 @@ glfwInit(monotonic_t start_time, bool *supports_window_occlusion) { return false; } - if (!_glfwPlatformCreateMutex(&_glfw.errorLock) || !_glfwPlatformCreateTls(&_glfw.errorSlot) || !_glfwPlatformCreateTls(&_glfw.contextSlot)) { + if (!_glfwPlatformCreateMutex(&_glfw.errorLock) || !_glfwPlatformCreateTls(&_glfw.errorSlot)) { terminate(); return false; } @@ -248,7 +244,6 @@ GLFWAPI void glfwInitHint(int hint, int value) { switch (hint) { case GLFW_JOYSTICK_HAT_BUTTONS: _glfwInitHints.hatButtons = value; return; - case GLFW_ANGLE_PLATFORM_TYPE: _glfwInitHints.angleType = value; return; case GLFW_DEBUG_KEYBOARD: _glfwInitHints.debugKeyboard = value; return; case GLFW_DEBUG_RENDERING: _glfwInitHints.debugRendering = value; return; case GLFW_COCOA_CHDIR_RESOURCES: _glfwInitHints.ns.chdir = value; return; diff --git a/glfw/internal.h b/glfw/internal.h index 4c5763a52..e49bf53e7 100644 --- a/glfw/internal.h +++ b/glfw/internal.h @@ -50,8 +50,6 @@ #define GLFW_INCLUDE_NONE #include "glfw3.h" -#define EGL_PRESENT_OPAQUE_EXT 0x31df - #define GLFW_MOD_REMAP_SZ 8 #define _GLFW_INSERT_FIRST 0 #define _GLFW_INSERT_LAST 1 @@ -68,9 +66,7 @@ typedef unsigned long long GLFWid; typedef struct _GLFWerror _GLFWerror; typedef struct _GLFWinitconfig _GLFWinitconfig; typedef struct _GLFWwndconfig _GLFWwndconfig; -typedef struct _GLFWctxconfig _GLFWctxconfig; typedef struct _GLFWfbconfig _GLFWfbconfig; -typedef struct _GLFWcontext _GLFWcontext; typedef struct _GLFWwindow _GLFWwindow; typedef struct _GLFWlibrary _GLFWlibrary; typedef struct _GLFWmonitor _GLFWmonitor; @@ -81,31 +77,6 @@ typedef struct _GLFWjoystick _GLFWjoystick; typedef struct _GLFWtls _GLFWtls; typedef struct _GLFWmutex _GLFWmutex; -typedef void (*_GLFWmakecontextcurrentfun)(_GLFWwindow *); -typedef void (*_GLFWswapbuffersfun)(_GLFWwindow *); -typedef void (*_GLFWswapintervalfun)(int); -typedef int (*_GLFWextensionsupportedfun)(const char *); -typedef GLFWglproc (*_GLFWgetprocaddressfun)(const char *); -typedef void (*_GLFWdestroycontextfun)(_GLFWwindow *); - -#define GL_VERSION 0x1F02 -#define GL_NONE 0 -#define GL_COLOR_BUFFER_BIT 0x00004000 -#define GL_UNSIGNED_BYTE 0x1401 -#define GL_EXTENSIONS 0x1F03 -#define GL_NUM_EXTENSIONS 0x821d -#define GL_CONTEXT_FLAGS 0x821e -#define GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT 0x00000001 -#define GL_CONTEXT_FLAG_DEBUG_BIT 0x00000002 -#define GL_CONTEXT_PROFILE_MASK 0x9126 -#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002 -#define GL_CONTEXT_CORE_PROFILE_BIT 0x00000001 -#define GL_RESET_NOTIFICATION_STRATEGY_ARB 0x8256 -#define GL_LOSE_CONTEXT_ON_RESET_ARB 0x8252 -#define GL_NO_RESET_NOTIFICATION_ARB 0x8261 -#define GL_CONTEXT_RELEASE_BEHAVIOR 0x82fb -#define GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH 0x82fc -#define GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR 0x00000008 #define MAX(x, y) \ __extension__({ \ @@ -120,17 +91,6 @@ typedef void (*_GLFWdestroycontextfun)(_GLFWwindow *); a < b ? a : b; \ }) -typedef int GLint; -typedef unsigned int GLuint; -typedef unsigned int GLenum; -typedef unsigned int GLbitfield; -typedef unsigned char GLubyte; - -typedef void(APIENTRY *PFNGLCLEARPROC)(GLbitfield); -typedef const GLubyte *(APIENTRY *PFNGLGETSTRINGPROC)(GLenum); -typedef void(APIENTRY *PFNGLGETINTEGERVPROC)(GLenum, GLint *); -typedef const GLubyte *(APIENTRY *PFNGLGETSTRINGIPROC)(GLenum, GLuint); - #define VK_NULL_HANDLE 0 typedef void *VkInstance; @@ -207,8 +167,6 @@ typedef VkResult(APIENTRY *PFN_vkEnumerateInstanceExtensionProperties)(const cha #error "No supported window creation API selected" #endif -#include "egl_context.h" -#include "osmesa_context.h" #define remove_i_from_array(array, i, count) \ { \ @@ -278,7 +236,6 @@ struct _GLFWerror { // struct _GLFWinitconfig { bool hatButtons; - int angleType; bool debugKeyboard; bool debugRendering; struct { @@ -320,6 +277,8 @@ struct _GLFWwndconfig { struct { char className[256]; char instanceName[256]; + // The visual to use for the window, chosen by the GPU driver, zero for the default + unsigned long visualID; } x11; struct { char appId[256], windowTag[256]; @@ -327,88 +286,13 @@ struct _GLFWwndconfig { } wl; }; -// Context configuration -// -// Parameters relating to the creation of the context but not directly related -// to the framebuffer. This is used to pass context creation parameters from -// shared code to the platform API. -// -struct _GLFWctxconfig { - int client; - int source; - int major; - int minor; - bool forward; - bool debug; - bool noerror; - int profile; - int robustness; - int release; - _GLFWwindow *share; - struct { - bool offline; - } nsgl; -}; - // Framebuffer configuration // -// This describes buffers and their sizes. It also contains -// a platform-specific ID used to map back to the backend API object. -// -// It is used to pass framebuffer parameters from shared code to the platform -// API and also to enumerate and select available framebuffer configs. -// struct _GLFWfbconfig { - int redBits; - int greenBits; - int blueBits; - int alphaBits; - int depthBits; - int stencilBits; - int accumRedBits; - int accumGreenBits; - int accumBlueBits; - int accumAlphaBits; - int auxBuffers; - bool stereo; - int samples; - bool sRGB; - bool doublebuffer; bool transparent; - uintptr_t handle; }; -// Context structure -// -struct _GLFWcontext { - int client; - int source; - int major, minor, revision; - bool forward, debug, noerror; - int profile; - int robustness; - int release; - - PFNGLGETSTRINGIPROC GetStringi; - PFNGLGETINTEGERVPROC GetIntegerv; - PFNGLGETSTRINGPROC GetString; - - _GLFWmakecontextcurrentfun makeCurrent; - _GLFWswapbuffersfun swapBuffers; - _GLFWswapintervalfun swapInterval; - _GLFWextensionsupportedfun extensionSupported; - _GLFWgetprocaddressfun getProcAddress; - _GLFWdestroycontextfun destroy; - - // This is defined in the context API's context.h - _GLFW_PLATFORM_CONTEXT_STATE - // This is defined in egl_context.h - _GLFWcontextEGL egl; - // This is defined in osmesa_context.h - _GLFWcontextOSMesa osmesa; -}; - -// Window and context structure +// Window structure // struct _GLFWwindow { struct _GLFWwindow *next; @@ -442,7 +326,6 @@ struct _GLFWwindow { double virtualCursorPosX, virtualCursorPosY; bool rawMouseMotion; - _GLFWcontext context; #ifdef _GLFW_WAYLAND bool swaps_disallowed; #else @@ -463,6 +346,7 @@ struct _GLFWwindow { GLFWwindowiconifyfun iconify; GLFWwindowmaximizefun maximize; GLFWframebuffersizefun fbsize; + GLFWnativesurfacechangedfun native_surface_changed; GLFWwindowcontentscalefun scale; GLFWmousebuttonfun mouseButton; GLFWcursorposfun cursorPos; @@ -579,7 +463,6 @@ struct _GLFWlibrary { _GLFWinitconfig init; _GLFWfbconfig framebuffer; _GLFWwndconfig window; - _GLFWctxconfig context; int refreshRate; } hints; @@ -599,7 +482,6 @@ struct _GLFWlibrary { int mappingCount; _GLFWtls errorSlot; - _GLFWtls contextSlot; _GLFWmutex errorLock; bool ignoreOSKeyboardProcessing, keyboard_grabbed; @@ -645,14 +527,8 @@ struct _GLFWlibrary { // This is defined in the window API's platform.h _GLFW_PLATFORM_LIBRARY_WINDOW_STATE; - // This is defined in the context API's context.h - _GLFW_PLATFORM_LIBRARY_CONTEXT_STATE // This is defined in the platform's joystick.h _GLFW_PLATFORM_LIBRARY_JOYSTICK_STATE - // This is defined in egl_context.h - _GLFWlibraryEGL egl; - // This is defined in osmesa_context.h - _GLFWlibraryOSMesa osmesa; struct { GLFWDragSourceItem *items; @@ -712,8 +588,7 @@ void _glfwPlatformTerminateJoysticks(void); int _glfwPlatformPollJoystick(_GLFWjoystick *js, int mode); void _glfwPlatformUpdateGamepadGUID(char *guid); -int _glfwPlatformCreateWindow( - _GLFWwindow *window, const _GLFWwndconfig *wndconfig, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig, const GLFWLayerShellConfig *lsc); +int _glfwPlatformCreateWindow(_GLFWwindow *window, const _GLFWwndconfig *wndconfig, const _GLFWfbconfig *fbconfig, const GLFWLayerShellConfig *lsc); void _glfwPlatformDestroyWindow(_GLFWwindow *window); void _glfwPlatformSetWindowTitle(_GLFWwindow *window, const char *title); void _glfwPlatformSetWindowIcon(_GLFWwindow *window, int count, const GLFWimage *images); @@ -760,15 +635,12 @@ void _glfwPlatformUpdateIMEState(_GLFWwindow *w, const GLFWIMEUpdateEvent *ev); void _glfwPlatformChangeCursorTheme(void); void _glfwPlatformTitlebarSettingsChanged(void); +void _glfwPlatformWindowContentsPresented(_GLFWwindow *window); void _glfwPlatformPollEvents(void); void _glfwPlatformWaitEvents(void); void _glfwPlatformWaitEventsTimeout(monotonic_t timeout); void _glfwPlatformPostEmptyEvent(void); -EGLenum _glfwPlatformGetEGLPlatform(EGLint **attribs); -EGLNativeDisplayType _glfwPlatformGetEGLNativeDisplay(void); -EGLNativeWindowType _glfwPlatformGetEGLNativeWindow(_GLFWwindow *window); - void _glfwPlatformGetRequiredInstanceExtensions(char **extensions); int _glfwPlatformGetPhysicalDevicePresentationSupport(VkInstance instance, VkPhysicalDevice device, uint32_t queuefamily); VkResult _glfwPlatformCreateWindowSurface(VkInstance instance, _GLFWwindow *window, const VkAllocationCallbacks *allocator, VkSurfaceKHR *surface); @@ -793,6 +665,7 @@ void _glfwInputWindowOcclusion(_GLFWwindow *window, bool occluded); void _glfwInputWindowPos(_GLFWwindow *window, int xpos, int ypos); void _glfwInputWindowSize(_GLFWwindow *window, int width, int height); void _glfwInputFramebufferSize(_GLFWwindow *window, int width, int height); +void _glfwInputNativeSurfaceChanged(_GLFWwindow *window); void _glfwInputWindowContentScale(_GLFWwindow *window, float xscale, float yscale); void _glfwInputWindowIconify(_GLFWwindow *window, bool iconified); void _glfwInputWindowMaximize(_GLFWwindow *window, bool maximized); @@ -851,9 +724,6 @@ void _glfwDebug(const char *format, ...); ////// GLFW internal API ////// ////////////////////////////////////////////////////////////////////////// -bool _glfwStringInExtensionString(const char *string, const char *extensions); -bool _glfwRefreshContextAttribs(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig); -bool _glfwIsValidContextConfig(const _GLFWctxconfig *ctxconfig); const GLFWvidmode *_glfwChooseVideoMode(_GLFWmonitor *monitor, const GLFWvidmode *desired); int _glfwCompareVideoModes(const GLFWvidmode *first, const GLFWvidmode *second); diff --git a/glfw/nsgl_context.h b/glfw/nsgl_context.h deleted file mode 100644 index fe8f4b887..000000000 --- a/glfw/nsgl_context.h +++ /dev/null @@ -1,51 +0,0 @@ -//======================================================================== -// GLFW 3.4 macOS - www.glfw.org -//------------------------------------------------------------------------ -// Copyright (c) 2009-2019 Camilla Löwy -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would -// be appreciated but is not required. -// -// 2. Altered source versions must be plainly marked as such, and must not -// be misrepresented as being the original software. -// -// 3. This notice may not be removed or altered from any source -// distribution. -// -//======================================================================== - -#define _GLFW_PLATFORM_CONTEXT_STATE _GLFWcontextNSGL nsgl; -#define _GLFW_PLATFORM_LIBRARY_CONTEXT_STATE _GLFWlibraryNSGL nsgl; - - -// NSGL-specific per-context data -// -typedef struct _GLFWcontextNSGL { - id pixelFormat; - id object; - -} _GLFWcontextNSGL; - -// NSGL-specific global data -// -typedef struct _GLFWlibraryNSGL { - // dlopen handle for OpenGL.framework (for glfwGetProcAddress) - CFBundleRef framework; - -} _GLFWlibraryNSGL; - - -bool _glfwInitNSGL(void); -void _glfwTerminateNSGL(void); -bool _glfwCreateContextNSGL(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig); -void _glfwDestroyContextNSGL(_GLFWwindow *window); diff --git a/glfw/nsgl_context.m b/glfw/nsgl_context.m deleted file mode 100644 index cb0f7c8fa..000000000 --- a/glfw/nsgl_context.m +++ /dev/null @@ -1,333 +0,0 @@ -//======================================================================== -// GLFW 3.4 macOS - www.glfw.org -//------------------------------------------------------------------------ -// Copyright (c) 2009-2019 Camilla Löwy -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would -// be appreciated but is not required. -// -// 2. Altered source versions must be plainly marked as such, and must not -// be misrepresented as being the original software. -// -// 3. This notice may not be removed or altered from any source -// distribution. -// -//======================================================================== -// It is fine to use C99 in this file because it will not be built with VS -//======================================================================== - -#include "internal.h" -#include - - -static void -makeContextCurrentNSGL(_GLFWwindow *window) { - if (window) [window->context.nsgl.object makeCurrentContext]; - else [NSOpenGLContext clearCurrentContext]; - - _glfwPlatformSetTls(&_glfw.contextSlot, window); -} - -static void -swapBuffersNSGL(_GLFWwindow *window) { - // ARP appears to be unnecessary, but this is future-proof - [window->context.nsgl.object flushBuffer]; -} - -static void -swapIntervalNSGL(int interval UNUSED) { - // As of Mojave this does not work so we use CVDisplayLink instead - _glfwInputError(GLFW_API_UNAVAILABLE, "NSGL: Swap intervals do not work on macOS"); -} - -static int -extensionSupportedNSGL(const char *extension UNUSED) { - // There are no NSGL extensions - return false; -} - -static GLFWglproc -getProcAddressNSGL(const char *procname) { - CFStringRef symbolName = CFStringCreateWithCString(kCFAllocatorDefault, procname, kCFStringEncodingASCII); - - GLFWglproc symbol; - *(void **)&symbol = CFBundleGetFunctionPointerForName(_glfw.nsgl.framework, symbolName); - - CFRelease(symbolName); - - return symbol; -} - -static void -destroyContextNSGL(_GLFWwindow *window) { - [window->context.nsgl.pixelFormat release]; - window->context.nsgl.pixelFormat = nil; - - [window->context.nsgl.object release]; - window->context.nsgl.object = nil; -} - - -////////////////////////////////////////////////////////////////////////// -////// GLFW internal API ////// -////////////////////////////////////////////////////////////////////////// - -// Initialize OpenGL support -// -bool -_glfwInitNSGL(void) { - if (_glfw.nsgl.framework) return true; - - _glfw.nsgl.framework = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl")); - if (_glfw.nsgl.framework == NULL) { - _glfwInputError(GLFW_API_UNAVAILABLE, "NSGL: Failed to locate OpenGL framework"); - return false; - } - - return true; -} - -// We use a globally shared context across all OS Windows so that -// if all OS Windows are closed the context does not have to be recreated -// with all associated data lost. On Apple kitty can remain running with no -// OS Windows. -static NSOpenGLContext *globally_shared_context = nil; - -// Terminate OpenGL support -// -void -_glfwTerminateNSGL(void) { - if (globally_shared_context != nil) { - [globally_shared_context release]; - globally_shared_context = nil; - } -} - - -// Create the OpenGL context -// -bool -_glfwCreateContextNSGL(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig) { - if (ctxconfig->client == GLFW_OPENGL_ES_API) { - _glfwInputError(GLFW_API_UNAVAILABLE, "NSGL: OpenGL ES is not available on macOS"); - return false; - } - - if (ctxconfig->major > 2) { - if (ctxconfig->major == 3 && ctxconfig->minor < 2) { - _glfwInputError(GLFW_VERSION_UNAVAILABLE, "NSGL: The targeted version of macOS does not support OpenGL 3.0 or 3.1 but may support 3.2 and above"); - return false; - } - } - - // Context robustness modes (GL_KHR_robustness) are not yet supported by - // macOS but are not a hard constraint, so ignore and continue - - // Context release behaviors (GL_KHR_context_flush_control) are not yet - // supported by macOS but are not a hard constraint, so ignore and continue - - // Debug contexts (GL_KHR_debug) are not yet supported by macOS but are not - // a hard constraint, so ignore and continue - - // No-error contexts (GL_KHR_no_error) are not yet supported by macOS but - // are not a hard constraint, so ignore and continue - -#define addAttrib(a) \ - { \ - assert((size_t)index < sizeof(attribs) / sizeof(attribs[0])); \ - attribs[index++] = a; \ - } -#define setAttrib(a, v) \ - { \ - addAttrib(a); \ - addAttrib(v); \ - } - - NSOpenGLPixelFormatAttribute attribs[40]; - int index = 0; - - addAttrib(NSOpenGLPFAAccelerated); - addAttrib(NSOpenGLPFAClosestPolicy); - - if (ctxconfig->nsgl.offline) { - addAttrib(NSOpenGLPFAAllowOfflineRenderers); - // NOTE: This replaces the NSSupportsAutomaticGraphicsSwitching key in - // Info.plist for unbundled applications - // HACK: This assumes that NSOpenGLPixelFormat will remain - // a straightforward wrapper of its CGL counterpart - addAttrib(kCGLPFASupportsAutomaticGraphicsSwitching); - } - -#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101000 - if (ctxconfig->major >= 4) { - setAttrib(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion4_1Core); - } else -#endif /*MAC_OS_X_VERSION_MAX_ALLOWED*/ - if (ctxconfig->major >= 3) { setAttrib(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core); } - - if (ctxconfig->major <= 2) { - if (fbconfig->auxBuffers != GLFW_DONT_CARE) setAttrib(NSOpenGLPFAAuxBuffers, fbconfig->auxBuffers); - - if (fbconfig->accumRedBits != GLFW_DONT_CARE && fbconfig->accumGreenBits != GLFW_DONT_CARE && fbconfig->accumBlueBits != GLFW_DONT_CARE && - fbconfig->accumAlphaBits != GLFW_DONT_CARE) { - const int accumBits = fbconfig->accumRedBits + fbconfig->accumGreenBits + fbconfig->accumBlueBits + fbconfig->accumAlphaBits; - - setAttrib(NSOpenGLPFAAccumSize, accumBits); - } - } - - if (fbconfig->redBits != GLFW_DONT_CARE && fbconfig->greenBits != GLFW_DONT_CARE && fbconfig->blueBits != GLFW_DONT_CARE) { - int colorBits = fbconfig->redBits + fbconfig->greenBits + fbconfig->blueBits; - - // macOS needs non-zero color size, so set reasonable values - if (colorBits == 0) colorBits = 24; - else if (colorBits < 15) colorBits = 15; - - setAttrib(NSOpenGLPFAColorSize, colorBits); - } - - if (fbconfig->alphaBits != GLFW_DONT_CARE) setAttrib(NSOpenGLPFAAlphaSize, fbconfig->alphaBits); - - if (fbconfig->depthBits != GLFW_DONT_CARE) setAttrib(NSOpenGLPFADepthSize, fbconfig->depthBits); - - if (fbconfig->stencilBits != GLFW_DONT_CARE) setAttrib(NSOpenGLPFAStencilSize, fbconfig->stencilBits); - - if (fbconfig->stereo) { -#if MAC_OS_X_VERSION_MAX_ALLOWED >= 101200 - _glfwInputError(GLFW_FORMAT_UNAVAILABLE, "NSGL: Stereo rendering is deprecated"); - return false; -#else - addAttrib(NSOpenGLPFAStereo); -#endif - } - - if (fbconfig->doublebuffer) addAttrib(NSOpenGLPFADoubleBuffer); - - if (fbconfig->samples != GLFW_DONT_CARE) { - if (fbconfig->samples == 0) { - setAttrib(NSOpenGLPFASampleBuffers, 0); - } else { - setAttrib(NSOpenGLPFASampleBuffers, 1); - setAttrib(NSOpenGLPFASamples, fbconfig->samples); - } - } - - // NOTE: All NSOpenGLPixelFormats on the relevant cards support sRGB - // framebuffer, so there's no need (and no way) to request it - - addAttrib(0); - -#undef addAttrib -#undef setAttrib - - window->context.nsgl.pixelFormat = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs]; - if (window->context.nsgl.pixelFormat == nil) { - _glfwInputError(GLFW_FORMAT_UNAVAILABLE, "NSGL: Failed to find a suitable pixel format"); - return false; - } - - NSOpenGLContext *share = globally_shared_context; - - if (ctxconfig->share) share = ctxconfig->share->context.nsgl.object; - - window->context.nsgl.object = [[NSOpenGLContext alloc] initWithFormat:window->context.nsgl.pixelFormat shareContext:share]; - if (window->context.nsgl.object == nil) { - _glfwInputError(GLFW_VERSION_UNAVAILABLE, "NSGL: Failed to create OpenGL context"); - return false; - } - if (globally_shared_context == nil) { globally_shared_context = [window->context.nsgl.object retain]; } - - if (fbconfig->transparent) { - GLint opaque = 0; - [window->context.nsgl.object setValues:&opaque forParameter:NSOpenGLContextParameterSurfaceOpacity]; - } - - [window->ns.view setWantsBestResolutionOpenGLSurface:window->ns.retina]; - - GLint interval = 0; - [window->context.nsgl.object setValues:&interval forParameter:NSOpenGLContextParameterSwapInterval]; - - [window->context.nsgl.object setView:window->ns.view]; - - window->context.makeCurrent = makeContextCurrentNSGL; - window->context.swapBuffers = swapBuffersNSGL; - window->context.swapInterval = swapIntervalNSGL; - window->context.extensionSupported = extensionSupportedNSGL; - window->context.getProcAddress = getProcAddressNSGL; - window->context.destroy = destroyContextNSGL; - - return true; -} - - -////////////////////////////////////////////////////////////////////////// -////// GLFW native API ////// -////////////////////////////////////////////////////////////////////////// - -GLFWAPI id -glfwGetNSGLContext(GLFWwindow *handle) { - _GLFWwindow *window = (_GLFWwindow *)handle; - assert(window != NULL); - - _GLFW_REQUIRE_INIT_OR_RETURN(nil); - - if (window->context.client == GLFW_NO_API) { - _glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL); - return nil; - } - - return window->context.nsgl.object; -} - -GLFWAPI bool -glfwCocoaRecreateGLDrawable(GLFWwindow *w) { - _GLFWwindow *window = (_GLFWwindow *)w; - if (window->context.client == GLFW_NO_API) return false; - @try { - // Save current state - NSOpenGLPixelFormat *pixelFormat = window->context.nsgl.pixelFormat; - NSOpenGLContext *oldContext = window->context.nsgl.object; - - // Create a new context sharing resources with the old one - NSOpenGLContext *newContext = [[NSOpenGLContext alloc] initWithFormat:pixelFormat shareContext:oldContext]; - if (newContext == nil) return false; - - // Copy settings from old context - GLint opacity = 0; - [oldContext getValues:&opacity forParameter:NSOpenGLContextParameterSurfaceOpacity]; - [newContext setValues:&opacity forParameter:NSOpenGLContextParameterSurfaceOpacity]; - GLint interval = 0; - [newContext setValues:&interval forParameter:NSOpenGLContextParameterSwapInterval]; - - // Detach old context - [NSOpenGLContext clearCurrentContext]; - [oldContext clearDrawable]; - - // Attach new context to the view - [window->ns.view setWantsBestResolutionOpenGLSurface:window->ns.retina]; -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - [newContext setView:window->ns.view]; -#pragma clang diagnostic pop - [newContext makeCurrentContext]; - [newContext update]; - - // Replace context - window->context.nsgl.object = newContext; - [oldContext release]; - } @catch (NSException *e) { - _glfwInputError(GLFW_PLATFORM_ERROR, "Failed to recreate NSGL context: %s (%s)", [[e name] UTF8String], [[e reason] UTF8String]); - return false; - } - return true; -} diff --git a/glfw/osmesa_context.c b/glfw/osmesa_context.c deleted file mode 100644 index c7b8d2c62..000000000 --- a/glfw/osmesa_context.c +++ /dev/null @@ -1,294 +0,0 @@ -//======================================================================== -// GLFW 3.4 OSMesa - www.glfw.org -//------------------------------------------------------------------------ -// Copyright (c) 2016 Google Inc. -// Copyright (c) 2016-2017 Camilla Löwy -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would -// be appreciated but is not required. -// -// 2. Altered source versions must be plainly marked as such, and must not -// be misrepresented as being the original software. -// -// 3. This notice may not be removed or altered from any source -// distribution. -// -//======================================================================== -// Please use C89 style variable declarations in this file because VS 2010 -//======================================================================== - -#include -#include -#include - -#include "internal.h" - - -static void -makeContextCurrentOSMesa(_GLFWwindow *window) { - if (window) { - int width, height; - _glfwPlatformGetFramebufferSize(window, &width, &height); - - // Check to see if we need to allocate a new buffer - if ((window->context.osmesa.buffer == NULL) || (width != window->context.osmesa.width) || (height != window->context.osmesa.height)) { - free(window->context.osmesa.buffer); - - // Allocate the new buffer (width * height * 8-bit RGBA) - window->context.osmesa.buffer = calloc(4, (size_t)width * height); - window->context.osmesa.width = width; - window->context.osmesa.height = height; - } - - if (!OSMesaMakeCurrent(window->context.osmesa.handle, window->context.osmesa.buffer, GL_UNSIGNED_BYTE, width, height)) { - _glfwInputError(GLFW_PLATFORM_ERROR, "OSMesa: Failed to make context current"); - return; - } - } - - _glfwPlatformSetTls(&_glfw.contextSlot, window); -} - -static GLFWglproc -getProcAddressOSMesa(const char *procname) { - return (GLFWglproc)OSMesaGetProcAddress(procname); -} - -static void -destroyContextOSMesa(_GLFWwindow *window) { - if (window->context.osmesa.handle) { - OSMesaDestroyContext(window->context.osmesa.handle); - window->context.osmesa.handle = NULL; - } - - if (window->context.osmesa.buffer) { - free(window->context.osmesa.buffer); - window->context.osmesa.width = 0; - window->context.osmesa.height = 0; - } -} - -static void -swapBuffersOSMesa(_GLFWwindow *window UNUSED) { - // No double buffering on OSMesa -} - -static void -swapIntervalOSMesa(int interval UNUSED) { - // No swap interval on OSMesa -} - -static int -extensionSupportedOSMesa(const char *extension UNUSED) { - // OSMesa does not have extensions - return false; -} - - -////////////////////////////////////////////////////////////////////////// -////// GLFW internal API ////// -////////////////////////////////////////////////////////////////////////// - -bool -_glfwInitOSMesa(void) { - int i; - const char *sonames[] = { -#if defined(_GLFW_OSMESA_LIBRARY) - _GLFW_OSMESA_LIBRARY, -#elif defined(_WIN32) - "libOSMesa.dll", - "OSMesa.dll", -#elif defined(__APPLE__) - "libOSMesa.8.dylib", -#elif defined(__CYGWIN__) - "libOSMesa-8.so", -#else - "libOSMesa.so.8", - "libOSMesa.so.6", -#endif - NULL}; - - if (_glfw.osmesa.handle) return true; - - for (i = 0; sonames[i]; i++) { - _glfw.osmesa.handle = _glfw_dlopen(sonames[i]); - if (_glfw.osmesa.handle) break; - } - - if (!_glfw.osmesa.handle) { - _glfwInputError(GLFW_API_UNAVAILABLE, "OSMesa: Library not found"); - return false; - } - - glfw_dlsym(_glfw.osmesa.CreateContextExt, _glfw.osmesa.handle, "OSMesaCreateContextExt"); - glfw_dlsym(_glfw.osmesa.CreateContextAttribs, _glfw.osmesa.handle, "OSMesaCreateContextAttribs"); - glfw_dlsym(_glfw.osmesa.DestroyContext, _glfw.osmesa.handle, "OSMesaDestroyContext"); - glfw_dlsym(_glfw.osmesa.MakeCurrent, _glfw.osmesa.handle, "OSMesaMakeCurrent"); - glfw_dlsym(_glfw.osmesa.GetColorBuffer, _glfw.osmesa.handle, "OSMesaGetColorBuffer"); - glfw_dlsym(_glfw.osmesa.GetDepthBuffer, _glfw.osmesa.handle, "OSMesaGetDepthBuffer"); - glfw_dlsym(_glfw.osmesa.GetProcAddress, _glfw.osmesa.handle, "OSMesaGetProcAddress"); - - if (!_glfw.osmesa.CreateContextExt || !_glfw.osmesa.DestroyContext || !_glfw.osmesa.MakeCurrent || !_glfw.osmesa.GetColorBuffer || - !_glfw.osmesa.GetDepthBuffer || !_glfw.osmesa.GetProcAddress) { - _glfwInputError(GLFW_PLATFORM_ERROR, "OSMesa: Failed to load required entry points"); - - _glfwTerminateOSMesa(); - return false; - } - - return true; -} - -void -_glfwTerminateOSMesa(void) { - if (_glfw.osmesa.handle) { - _glfw_dlclose(_glfw.osmesa.handle); - _glfw.osmesa.handle = NULL; - } -} - -#define setAttrib(a, v) \ - { \ - assert(((size_t)index + 1) < sizeof(attribs) / sizeof(attribs[0])); \ - attribs[index++] = a; \ - attribs[index++] = v; \ - } - -bool -_glfwCreateContextOSMesa(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig) { - OSMesaContext share = NULL; - const int accumBits = fbconfig->accumRedBits + fbconfig->accumGreenBits + fbconfig->accumBlueBits + fbconfig->accumAlphaBits; - - if (ctxconfig->client == GLFW_OPENGL_ES_API) { - _glfwInputError(GLFW_API_UNAVAILABLE, "OSMesa: OpenGL ES is not available on OSMesa"); - return false; - } - - if (ctxconfig->share) share = ctxconfig->share->context.osmesa.handle; - - if (OSMesaCreateContextAttribs) { - int index = 0, attribs[40]; - - setAttrib(OSMESA_FORMAT, OSMESA_RGBA); - setAttrib(OSMESA_DEPTH_BITS, fbconfig->depthBits); - setAttrib(OSMESA_STENCIL_BITS, fbconfig->stencilBits); - setAttrib(OSMESA_ACCUM_BITS, accumBits); - - if (ctxconfig->profile == GLFW_OPENGL_CORE_PROFILE) { - setAttrib(OSMESA_PROFILE, OSMESA_CORE_PROFILE); - } else if (ctxconfig->profile == GLFW_OPENGL_COMPAT_PROFILE) { - setAttrib(OSMESA_PROFILE, OSMESA_COMPAT_PROFILE); - } - - if (ctxconfig->major != 1 || ctxconfig->minor != 0) { - setAttrib(OSMESA_CONTEXT_MAJOR_VERSION, ctxconfig->major); - setAttrib(OSMESA_CONTEXT_MINOR_VERSION, ctxconfig->minor); - } - - if (ctxconfig->forward) { - _glfwInputError(GLFW_VERSION_UNAVAILABLE, "OSMesa: Forward-compatible contexts not supported"); - return false; - } - - setAttrib(0, 0); - - window->context.osmesa.handle = OSMesaCreateContextAttribs(attribs, share); - } else { - if (ctxconfig->profile) { - _glfwInputError(GLFW_VERSION_UNAVAILABLE, "OSMesa: OpenGL profiles unavailable"); - return false; - } - - window->context.osmesa.handle = OSMesaCreateContextExt(OSMESA_RGBA, fbconfig->depthBits, fbconfig->stencilBits, accumBits, share); - } - - if (window->context.osmesa.handle == NULL) { - _glfwInputError(GLFW_VERSION_UNAVAILABLE, "OSMesa: Failed to create context"); - return false; - } - - window->context.makeCurrent = makeContextCurrentOSMesa; - window->context.swapBuffers = swapBuffersOSMesa; - window->context.swapInterval = swapIntervalOSMesa; - window->context.extensionSupported = extensionSupportedOSMesa; - window->context.getProcAddress = getProcAddressOSMesa; - window->context.destroy = destroyContextOSMesa; - - return true; -} - -#undef setAttrib - - -////////////////////////////////////////////////////////////////////////// -////// GLFW native API ////// -////////////////////////////////////////////////////////////////////////// - -GLFWAPI int -glfwGetOSMesaColorBuffer(GLFWwindow *handle, int *width, int *height, int *format, void **buffer) { - void *mesaBuffer; - GLint mesaWidth, mesaHeight, mesaFormat; - _GLFWwindow *window = (_GLFWwindow *)handle; - assert(window != NULL); - - _GLFW_REQUIRE_INIT_OR_RETURN(false); - - if (!OSMesaGetColorBuffer(window->context.osmesa.handle, &mesaWidth, &mesaHeight, &mesaFormat, &mesaBuffer)) { - _glfwInputError(GLFW_PLATFORM_ERROR, "OSMesa: Failed to retrieve color buffer"); - return false; - } - - if (width) *width = mesaWidth; - if (height) *height = mesaHeight; - if (format) *format = mesaFormat; - if (buffer) *buffer = mesaBuffer; - - return true; -} - -GLFWAPI int -glfwGetOSMesaDepthBuffer(GLFWwindow *handle, int *width, int *height, int *bytesPerValue, void **buffer) { - void *mesaBuffer; - GLint mesaWidth, mesaHeight, mesaBytes; - _GLFWwindow *window = (_GLFWwindow *)handle; - assert(window != NULL); - - _GLFW_REQUIRE_INIT_OR_RETURN(false); - - if (!OSMesaGetDepthBuffer(window->context.osmesa.handle, &mesaWidth, &mesaHeight, &mesaBytes, &mesaBuffer)) { - _glfwInputError(GLFW_PLATFORM_ERROR, "OSMesa: Failed to retrieve depth buffer"); - return false; - } - - if (width) *width = mesaWidth; - if (height) *height = mesaHeight; - if (bytesPerValue) *bytesPerValue = mesaBytes; - if (buffer) *buffer = mesaBuffer; - - return true; -} - -GLFWAPI OSMesaContext -glfwGetOSMesaContext(GLFWwindow *handle) { - _GLFWwindow *window = (_GLFWwindow *)handle; - assert(window != NULL); - - _GLFW_REQUIRE_INIT_OR_RETURN(NULL); - - if (window->context.client == GLFW_NO_API) { - _glfwInputError(GLFW_NO_WINDOW_CONTEXT, NULL); - return NULL; - } - - return window->context.osmesa.handle; -} diff --git a/glfw/osmesa_context.h b/glfw/osmesa_context.h deleted file mode 100644 index 68a118563..000000000 --- a/glfw/osmesa_context.h +++ /dev/null @@ -1,85 +0,0 @@ -//======================================================================== -// GLFW 3.4 OSMesa - www.glfw.org -//------------------------------------------------------------------------ -// Copyright (c) 2016 Google Inc. -// Copyright (c) 2016-2017 Camilla Löwy -// -// This software is provided 'as-is', without any express or implied -// warranty. In no event will the authors be held liable for any damages -// arising from the use of this software. -// -// Permission is granted to anyone to use this software for any purpose, -// including commercial applications, and to alter it and redistribute it -// freely, subject to the following restrictions: -// -// 1. The origin of this software must not be misrepresented; you must not -// claim that you wrote the original software. If you use this software -// in a product, an acknowledgment in the product documentation would -// be appreciated but is not required. -// -// 2. Altered source versions must be plainly marked as such, and must not -// be misrepresented as being the original software. -// -// 3. This notice may not be removed or altered from any source -// distribution. -// -//======================================================================== - -#define OSMESA_RGBA 0x1908 -#define OSMESA_FORMAT 0x22 -#define OSMESA_DEPTH_BITS 0x30 -#define OSMESA_STENCIL_BITS 0x31 -#define OSMESA_ACCUM_BITS 0x32 -#define OSMESA_PROFILE 0x33 -#define OSMESA_CORE_PROFILE 0x34 -#define OSMESA_COMPAT_PROFILE 0x35 -#define OSMESA_CONTEXT_MAJOR_VERSION 0x36 -#define OSMESA_CONTEXT_MINOR_VERSION 0x37 - -typedef void *OSMesaContext; -typedef void (*OSMESAproc)(void); - -typedef OSMesaContext(GLAPIENTRY *PFN_OSMesaCreateContextExt)(GLenum, GLint, GLint, GLint, OSMesaContext); -typedef OSMesaContext(GLAPIENTRY *PFN_OSMesaCreateContextAttribs)(const int *, OSMesaContext); -typedef void(GLAPIENTRY *PFN_OSMesaDestroyContext)(OSMesaContext); -typedef int(GLAPIENTRY *PFN_OSMesaMakeCurrent)(OSMesaContext, void *, int, int, int); -typedef int(GLAPIENTRY *PFN_OSMesaGetColorBuffer)(OSMesaContext, int *, int *, int *, void **); -typedef int(GLAPIENTRY *PFN_OSMesaGetDepthBuffer)(OSMesaContext, int *, int *, int *, void **); -typedef GLFWglproc(GLAPIENTRY *PFN_OSMesaGetProcAddress)(const char *); -#define OSMesaCreateContextExt _glfw.osmesa.CreateContextExt -#define OSMesaCreateContextAttribs _glfw.osmesa.CreateContextAttribs -#define OSMesaDestroyContext _glfw.osmesa.DestroyContext -#define OSMesaMakeCurrent _glfw.osmesa.MakeCurrent -#define OSMesaGetColorBuffer _glfw.osmesa.GetColorBuffer -#define OSMesaGetDepthBuffer _glfw.osmesa.GetDepthBuffer -#define OSMesaGetProcAddress _glfw.osmesa.GetProcAddress - -// OSMesa-specific per-context data -// -typedef struct _GLFWcontextOSMesa { - OSMesaContext handle; - int width; - int height; - void *buffer; - -} _GLFWcontextOSMesa; - -// OSMesa-specific global data -// -typedef struct _GLFWlibraryOSMesa { - void *handle; - - PFN_OSMesaCreateContextExt CreateContextExt; - PFN_OSMesaCreateContextAttribs CreateContextAttribs; - PFN_OSMesaDestroyContext DestroyContext; - PFN_OSMesaMakeCurrent MakeCurrent; - PFN_OSMesaGetColorBuffer GetColorBuffer; - PFN_OSMesaGetDepthBuffer GetDepthBuffer; - PFN_OSMesaGetProcAddress GetProcAddress; - -} _GLFWlibraryOSMesa; - - -bool _glfwInitOSMesa(void); -void _glfwTerminateOSMesa(void); -bool _glfwCreateContextOSMesa(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig); diff --git a/glfw/source-info.json b/glfw/source-info.json index 43a97b550..20b179520 100644 --- a/glfw/source-info.json +++ b/glfw/source-info.json @@ -3,10 +3,7 @@ "headers": [ "cocoa_platform.h", "cocoa_joystick.h", - "posix_thread.h", - "nsgl_context.h", - "egl_context.h", - "osmesa_context.h" + "posix_thread.h" ], "sources": [ "cocoa_init.m", @@ -14,10 +11,7 @@ "cocoa_monitor.m", "cocoa_window.m", "cocoa_displaylink.m", - "posix_thread.c", - "nsgl_context.m", - "egl_context.c", - "osmesa_context.c" + "posix_thread.c" ] }, "common": { @@ -26,7 +20,6 @@ "mappings.h" ], "sources": [ - "context.c", "init.c", "input.c", "monitor.c", @@ -45,8 +38,6 @@ "dbus_glfw.h", "ibus_glfw.h", "backend_utils.h", - "egl_context.h", - "osmesa_context.h", "linux_joystick.h", "null_joystick.h", "linux_notify.h", @@ -93,8 +84,6 @@ "xkb_glfw.c", "dbus_glfw.c", "ibus_glfw.c", - "egl_context.c", - "osmesa_context.c", "backend_utils.c", "linux_joystick.c", "linux_desktop_settings.c", @@ -117,9 +106,6 @@ "ibus_glfw.h", "backend_utils.h", "posix_thread.h", - "glx_context.h", - "egl_context.h", - "osmesa_context.h", "linux_joystick.h", "null_joystick.h", "linux_notify.h", @@ -135,9 +121,6 @@ "dbus_glfw.c", "ibus_glfw.c", "posix_thread.c", - "glx_context.c", - "egl_context.c", - "osmesa_context.c", "backend_utils.c", "linux_joystick.c", "null_joystick.c", diff --git a/glfw/vulkan.c b/glfw/vulkan.c index 6a84c7860..92d9923ac 100644 --- a/glfw/vulkan.c +++ b/glfw/vulkan.c @@ -250,10 +250,5 @@ glfwCreateWindowSurface(VkInstance instance, GLFWwindow *handle, const VkAllocat return VK_ERROR_EXTENSION_NOT_PRESENT; } - if (window->context.client != GLFW_NO_API) { - _glfwInputError(GLFW_INVALID_VALUE, "Vulkan: Window surface creation requires the window to have the client API set to GLFW_NO_API"); - return VK_ERROR_NATIVE_WINDOW_IN_USE_KHR; - } - return _glfwPlatformCreateWindowSurface(instance, window, allocator, surface); } diff --git a/glfw/window.c b/glfw/window.c index c97a0551d..5a3d42c66 100644 --- a/glfw/window.c +++ b/glfw/window.c @@ -136,6 +136,13 @@ _glfwInputFramebufferSize(_GLFWwindow *window, int width, int height) { if (window->callbacks.fbsize) window->callbacks.fbsize((GLFWwindow *)window, width, height); } +// Notifies shared code that the native surface of a window changed in a way +// that requires the GPU driver to update its drawable +void +_glfwInputNativeSurfaceChanged(_GLFWwindow *window) { + if (window->callbacks.native_surface_changed) window->callbacks.native_surface_changed((GLFWwindow *)window); +} + // Notifies shared code that a window live resize is in progress // void @@ -179,9 +186,8 @@ _glfwInputWindowMonitor(_GLFWwindow *window, _GLFWmonitor *monitor) { ////////////////////////////////////////////////////////////////////////// GLFWAPI GLFWwindow * -glfwCreateWindow(int width, int height, const char *title, GLFWmonitor *monitor, GLFWwindow *share, const GLFWLayerShellConfig *lsc) { +glfwCreateWindow(int width, int height, const char *title, GLFWmonitor *monitor, const GLFWLayerShellConfig *lsc) { _GLFWfbconfig fbconfig; - _GLFWctxconfig ctxconfig; _GLFWwndconfig wndconfig; _GLFWwindow *window; @@ -198,15 +204,11 @@ glfwCreateWindow(int width, int height, const char *title, GLFWmonitor *monitor, } fbconfig = _glfw.hints.framebuffer; - ctxconfig = _glfw.hints.context; wndconfig = _glfw.hints.window; wndconfig.width = width; wndconfig.height = height; wndconfig.title = title; - ctxconfig.share = (_GLFWwindow *)share; - - if (!_glfwIsValidContextConfig(&ctxconfig)) return NULL; static GLFWid windowIdCounter = 0; window = calloc(1, sizeof(_GLFWwindow)); @@ -216,9 +218,9 @@ glfwCreateWindow(int width, int height, const char *title, GLFWmonitor *monitor, window->videoMode.width = width; window->videoMode.height = height; - window->videoMode.redBits = fbconfig.redBits; - window->videoMode.greenBits = fbconfig.greenBits; - window->videoMode.blueBits = fbconfig.blueBits; + window->videoMode.redBits = 8; + window->videoMode.greenBits = 8; + window->videoMode.blueBits = 8; window->videoMode.refreshRate = _glfw.hints.refreshRate; window->monitor = (_GLFWmonitor *)monitor; @@ -239,19 +241,12 @@ glfwCreateWindow(int width, int height, const char *title, GLFWmonitor *monitor, window->widthincr = GLFW_DONT_CARE; window->heightincr = GLFW_DONT_CARE; - // Open the actual window and create its context - if (!_glfwPlatformCreateWindow(window, &wndconfig, &ctxconfig, &fbconfig, lsc)) { + // Open the actual window + if (!_glfwPlatformCreateWindow(window, &wndconfig, &fbconfig, lsc)) { glfwDestroyWindow((GLFWwindow *)window); return NULL; } - if (ctxconfig.client != GLFW_NO_API) { - if (!_glfwRefreshContextAttribs(window, &ctxconfig)) { - glfwDestroyWindow((GLFWwindow *)window); - return NULL; - } - } - if (wndconfig.mousePassthrough) _glfwPlatformSetWindowMousePassthrough(window, true); if (window->monitor) { @@ -272,13 +267,6 @@ void glfwDefaultWindowHints(void) { _GLFW_REQUIRE_INIT(); - // The default is OpenGL with minimum version 1.0 - memset(&_glfw.hints.context, 0, sizeof(_glfw.hints.context)); - _glfw.hints.context.client = GLFW_OPENGL_API; - _glfw.hints.context.source = GLFW_NATIVE_CONTEXT_API; - _glfw.hints.context.major = 1; - _glfw.hints.context.minor = 0; - // The default is a focused, visible, resizable window with decorations memset(&_glfw.hints.window, 0, sizeof(_glfw.hints.window)); _glfw.hints.window.resizable = true; @@ -290,16 +278,7 @@ glfwDefaultWindowHints(void) { _glfw.hints.window.focusOnShow = true; _glfw.hints.window.blur_radius = 0; - // The default is 24 bits of color, 24 bits of depth and 8 bits of stencil, - // double buffered memset(&_glfw.hints.framebuffer, 0, sizeof(_glfw.hints.framebuffer)); - _glfw.hints.framebuffer.redBits = 8; - _glfw.hints.framebuffer.greenBits = 8; - _glfw.hints.framebuffer.blueBits = 8; - _glfw.hints.framebuffer.alphaBits = 8; - _glfw.hints.framebuffer.depthBits = 24; - _glfw.hints.framebuffer.stencilBits = 8; - _glfw.hints.framebuffer.doublebuffer = true; // The default is to select the highest available refresh rate _glfw.hints.refreshRate = GLFW_DONT_CARE; @@ -315,22 +294,7 @@ glfwWindowHint(int hint, int value) { _GLFW_REQUIRE_INIT(); switch (hint) { - case GLFW_RED_BITS: _glfw.hints.framebuffer.redBits = value; return; - case GLFW_GREEN_BITS: _glfw.hints.framebuffer.greenBits = value; return; - case GLFW_BLUE_BITS: _glfw.hints.framebuffer.blueBits = value; return; - case GLFW_ALPHA_BITS: _glfw.hints.framebuffer.alphaBits = value; return; - case GLFW_DEPTH_BITS: _glfw.hints.framebuffer.depthBits = value; return; - case GLFW_STENCIL_BITS: _glfw.hints.framebuffer.stencilBits = value; return; - case GLFW_ACCUM_RED_BITS: _glfw.hints.framebuffer.accumRedBits = value; return; - case GLFW_ACCUM_GREEN_BITS: _glfw.hints.framebuffer.accumGreenBits = value; return; - case GLFW_ACCUM_BLUE_BITS: _glfw.hints.framebuffer.accumBlueBits = value; return; - case GLFW_ACCUM_ALPHA_BITS: _glfw.hints.framebuffer.accumAlphaBits = value; return; - case GLFW_AUX_BUFFERS: _glfw.hints.framebuffer.auxBuffers = value; return; - case GLFW_STEREO: _glfw.hints.framebuffer.stereo = value ? true : false; return; - case GLFW_DOUBLEBUFFER: _glfw.hints.framebuffer.doublebuffer = value ? true : false; return; case GLFW_TRANSPARENT_FRAMEBUFFER: _glfw.hints.framebuffer.transparent = value ? true : false; return; - case GLFW_SAMPLES: _glfw.hints.framebuffer.samples = value; return; - case GLFW_SRGB_CAPABLE: _glfw.hints.framebuffer.sRGB = value ? true : false; return; case GLFW_RESIZABLE: _glfw.hints.window.resizable = value ? true : false; return; case GLFW_DECORATED: _glfw.hints.window.decorated = value ? true : false; return; case GLFW_FOCUSED: _glfw.hints.window.focused = value ? true : false; return; @@ -341,23 +305,13 @@ glfwWindowHint(int hint, int value) { case GLFW_COCOA_RETINA_FRAMEBUFFER: _glfw.hints.window.ns.retina = value ? true : false; return; case GLFW_COCOA_COLOR_SPACE: _glfw.hints.window.ns.color_space = value; return; case GLFW_BLUR_RADIUS: _glfw.hints.window.blur_radius = value; return; - case GLFW_COCOA_GRAPHICS_SWITCHING: _glfw.hints.context.nsgl.offline = value ? true : false; return; case GLFW_SCALE_TO_MONITOR: _glfw.hints.window.scaleToMonitor = value ? true : false; return; case GLFW_CENTER_CURSOR: _glfw.hints.window.centerCursor = value ? true : false; return; case GLFW_FOCUS_ON_SHOW: _glfw.hints.window.focusOnShow = value ? true : false; return; case GLFW_MOUSE_PASSTHROUGH: _glfw.hints.window.mousePassthrough = value ? true : false; return; - case GLFW_CLIENT_API: _glfw.hints.context.client = value; return; - case GLFW_CONTEXT_CREATION_API: _glfw.hints.context.source = value; return; - case GLFW_CONTEXT_VERSION_MAJOR: _glfw.hints.context.major = value; return; - case GLFW_CONTEXT_VERSION_MINOR: _glfw.hints.context.minor = value; return; - case GLFW_CONTEXT_ROBUSTNESS: _glfw.hints.context.robustness = value; return; - case GLFW_OPENGL_FORWARD_COMPAT: _glfw.hints.context.forward = value ? true : false; return; - case GLFW_CONTEXT_DEBUG: _glfw.hints.context.debug = value ? true : false; return; - case GLFW_CONTEXT_NO_ERROR: _glfw.hints.context.noerror = value ? true : false; return; - case GLFW_OPENGL_PROFILE: _glfw.hints.context.profile = value; return; - case GLFW_CONTEXT_RELEASE_BEHAVIOR: _glfw.hints.context.release = value; return; case GLFW_REFRESH_RATE: _glfw.hints.refreshRate = value; return; case GLFW_WAYLAND_BGCOLOR: _glfw.hints.window.wl.bgcolor = value; return; + case GLFW_X11_VISUAL_ID: _glfw.hints.window.x11.visualID = (unsigned long)value; return; } _glfwInputError(GLFW_INVALID_ENUM, "Invalid window hint 0x%08X", hint); } @@ -391,10 +345,6 @@ glfwDestroyWindow(GLFWwindow *handle) { // Clear all callbacks to avoid exposing a half torn-down window object memset(&window->callbacks, 0, sizeof(window->callbacks)); - // The window's context must not be current on another thread when the - // window is destroyed - if (window == _glfwPlatformGetTls(&_glfw.contextSlot)) glfwMakeContextCurrent(NULL); - _glfwPlatformDestroyWindow(window); // Unlink window from global linked list @@ -770,17 +720,6 @@ glfwGetWindowAttrib(GLFWwindow *handle, int attrib) { case GLFW_DECORATED: return window->decorated; case GLFW_FLOATING: return window->floating; case GLFW_AUTO_ICONIFY: return window->autoIconify; - case GLFW_CLIENT_API: return window->context.client; - case GLFW_CONTEXT_CREATION_API: return window->context.source; - case GLFW_CONTEXT_VERSION_MAJOR: return window->context.major; - case GLFW_CONTEXT_VERSION_MINOR: return window->context.minor; - case GLFW_CONTEXT_REVISION: return window->context.revision; - case GLFW_CONTEXT_ROBUSTNESS: return window->context.robustness; - case GLFW_OPENGL_FORWARD_COMPAT: return window->context.forward; - case GLFW_CONTEXT_DEBUG: return window->context.debug; - case GLFW_OPENGL_PROFILE: return window->context.profile; - case GLFW_CONTEXT_RELEASE_BEHAVIOR: return window->context.release; - case GLFW_CONTEXT_NO_ERROR: return window->context.noerror; } _glfwInputError(GLFW_INVALID_ENUM, "Invalid window attribute 0x%08X", attrib); @@ -992,6 +931,24 @@ glfwSetFramebufferSizeCallback(GLFWwindow *handle, GLFWframebuffersizefun cbfun) return cbfun; } +GLFWAPI GLFWnativesurfacechangedfun +glfwSetNativeSurfaceChangedCallback(GLFWwindow *handle, GLFWnativesurfacechangedfun cbfun) { + _GLFWwindow *window = (_GLFWwindow *)handle; + assert(window != NULL); + + _GLFW_REQUIRE_INIT_OR_RETURN(NULL); + _GLFW_SWAP_POINTERS(window->callbacks.native_surface_changed, cbfun); + return cbfun; +} + +GLFWAPI void +glfwWindowContentsPresented(GLFWwindow *handle) { + _GLFWwindow *window = (_GLFWwindow *)handle; + assert(window != NULL); + _GLFW_REQUIRE_INIT(); + _glfwPlatformWindowContentsPresented(window); +} + GLFWAPI GLFWliveresizefun glfwSetLiveResizeCallback(GLFWwindow *handle, GLFWliveresizefun cbfun) { _GLFWwindow *window = (_GLFWwindow *)handle; diff --git a/glfw/wl_init.c b/glfw/wl_init.c index bd29c4029..f6472371d 100644 --- a/glfw/wl_init.c +++ b/glfw/wl_init.c @@ -1025,16 +1025,6 @@ _glfwPlatformInit(bool *supports_window_occlusion) { glfw_dlsym(_glfw.wl.cursor.theme_get_cursor, _glfw.wl.cursor.handle, "wl_cursor_theme_get_cursor"); glfw_dlsym(_glfw.wl.cursor.image_get_buffer, _glfw.wl.cursor.handle, "wl_cursor_image_get_buffer"); - _glfw.wl.egl.handle = _glfw_dlopen("libwayland-egl.so.1"); - if (!_glfw.wl.egl.handle) { - _glfwInputError(GLFW_PLATFORM_ERROR, "Wayland: Failed to open libwayland-egl"); - return false; - } - - glfw_dlsym(_glfw.wl.egl.window_create, _glfw.wl.egl.handle, "wl_egl_window_create"); - glfw_dlsym(_glfw.wl.egl.window_destroy, _glfw.wl.egl.handle, "wl_egl_window_destroy"); - glfw_dlsym(_glfw.wl.egl.window_resize, _glfw.wl.egl.handle, "wl_egl_window_resize"); - _glfw.wl.display = wl_display_connect(NULL); if (!_glfw.wl.display) { _glfwInputError(GLFW_PLATFORM_ERROR, "Wayland: Failed to connect to display"); @@ -1161,29 +1151,14 @@ _glfwPlatformTerminate(void) { if (_glfw.wl.pointer_gestures) zwp_pointer_gestures_v1_release(_glfw.wl.pointer_gestures); if (_glfw.wl.registry) wl_registry_destroy(_glfw.wl.registry); - // Call eglTerminate before disconnecting from the display: eglTerminate - // sends Wayland protocol requests which must be flushed and their closures - // drained before we unload the EGL library. The dlclose calls move to - // after wl_display_disconnect so the message format tables remain mapped - // while the queue is drained, preventing a segfault in - // destroy_queued_closure(). - if (_glfw.egl.display) { - eglTerminate(_glfw.egl.display); - _glfw.egl.display = EGL_NO_DISPLAY; - } + // The GPU driver must have released all its resources, such as EGL + // displays, before this is called, since they can send Wayland protocol + // requests that must be flushed and drained before disconnecting. if (_glfw.wl.display) { wl_display_flush(_glfw.wl.display); wl_display_disconnect(_glfw.wl.display); _glfw.wl.display = NULL; } - if (_glfw.egl.handle) { - _glfw_dlclose(_glfw.egl.handle); - _glfw.egl.handle = NULL; - } - if (_glfw.wl.egl.handle) { - _glfw_dlclose(_glfw.wl.egl.handle); - _glfw.wl.egl.handle = NULL; - } finalizePollData(&_glfw.wl.eventLoopData); if (_glfw.wl.compositor_name) { free(_glfw.wl.compositor_name); @@ -1197,7 +1172,7 @@ _glfwPlatformTerminate(void) { const char * _glfwPlatformGetVersionString(void) { (void)keep_going; - return _GLFW_VERSION_NUMBER " Wayland EGL OSMesa" + return _GLFW_VERSION_NUMBER " Wayland" #if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK) " clock_gettime" #else diff --git a/glfw/wl_platform.h b/glfw/wl_platform.h index 6bef7e6a2..d0c1ded34 100644 --- a/glfw/wl_platform.h +++ b/glfw/wl_platform.h @@ -96,12 +96,6 @@ typedef struct wl_buffer *(*PFN_wl_cursor_image_get_buffer)(struct wl_cursor_ima #define wl_cursor_theme_get_cursor _glfw.wl.cursor.theme_get_cursor #define wl_cursor_image_get_buffer _glfw.wl.cursor.image_get_buffer -typedef struct wl_egl_window *(*PFN_wl_egl_window_create)(struct wl_surface *, int, int); -typedef void (*PFN_wl_egl_window_destroy)(struct wl_egl_window *); -typedef void (*PFN_wl_egl_window_resize)(struct wl_egl_window *, int, int, int, int); -#define wl_egl_window_create _glfw.wl.egl.window_create -#define wl_egl_window_destroy _glfw.wl.egl.window_destroy -#define wl_egl_window_resize _glfw.wl.egl.window_resize typedef enum _GLFWCSDSurface { CENTRAL_WINDOW, @@ -179,7 +173,6 @@ typedef struct _GLFWwindowWayland { bool transparent; struct wl_surface *surface; bool waiting_for_swap_to_commit; - struct wl_egl_window *native; struct wl_callback *callback; struct { @@ -456,14 +449,6 @@ typedef struct _GLFWlibraryWayland { PFN_wl_cursor_image_get_buffer image_get_buffer; } cursor; - struct { - void *handle; - - PFN_wl_egl_window_create window_create; - PFN_wl_egl_window_destroy window_destroy; - PFN_wl_egl_window_resize window_resize; - } egl; - struct { glfw_wl_xdg_activation_request *array; size_t capacity, sz; diff --git a/glfw/wl_window.c b/glfw/wl_window.c index 82f5eb22c..f1a91806b 100644 --- a/glfw/wl_window.c +++ b/glfw/wl_window.c @@ -401,12 +401,6 @@ wait_for_swap_to_commit(_GLFWwindow *window) { static void resizeFramebuffer(_GLFWwindow *window) { - GLFWwindow *ctx = glfwGetCurrentContext(); - bool ctx_changed = false; - if (ctx != (GLFWwindow *)window && window->context.client != GLFW_NO_API) { - ctx_changed = true; - glfwMakeContextCurrent((GLFWwindow *)window); - } double scale = _glfwWaylandWindowScale(window); int scaled_width = (int)round(window->wl.width * scale); int scaled_height = (int)round(window->wl.height * scale); @@ -418,10 +412,9 @@ resizeFramebuffer(_GLFWwindow *window) { window->wl.width, window->wl.height, scale); - wl_egl_window_resize(window->wl.native, scaled_width, scaled_height, 0, 0); update_regions(window); wait_for_swap_to_commit(window); - if (ctx_changed) glfwMakeContextCurrent(ctx); + // The GPU driver resizes its buffers in response to this _glfwInputFramebufferSize(window, scaled_width, scaled_height); } @@ -728,9 +721,6 @@ create_surface(_GLFWwindow *window, const _GLFWwndconfig *wndconfig) { } debug("Creating window %llu at size: %dx%d and scale %d\n", window->id, wndconfig->width, wndconfig->height, scale); - window->wl.native = wl_egl_window_create(window->wl.surface, wndconfig->width * scale, wndconfig->height * scale); - if (!window->wl.native) return false; - window->wl.width = wndconfig->width; window->wl.height = wndconfig->height; window->wl.user_requested_content_size.width = wndconfig->width; @@ -1035,16 +1025,12 @@ attach_temp_buffer_during_window_creation(_GLFWwindow *window) { static void loop_till_window_fully_created(_GLFWwindow *window) { if (!window->wl.window_fully_created) { - GLFWwindow *ctx = glfwGetCurrentContext(); debug("Waiting for compositor to send fractional scale for window %llu\n", window->id); monotonic_t start = monotonic(); while (!window->wl.window_fully_created && monotonic() - start < ms_to_monotonic_t(300)) { if (wl_display_roundtrip(_glfw.wl.display) == -1) { window->wl.window_fully_created = true; } } window->wl.window_fully_created = true; - // If other OS windows were resized when this window is shown, the ctx might have been changed by - // user code, restore it to whatever it was at the start. - if (glfwGetCurrentContext() != ctx) glfwMakeContextCurrent(ctx); } } @@ -1545,21 +1531,8 @@ _glfwLoadCursor(GLFWCursorShape shape, struct wl_cursor_theme *theme) { ////// GLFW platform API ////// ////////////////////////////////////////////////////////////////////////// -static bool -attach_opengl_context_to_window(_GLFWwindow *window, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig) { - if (ctxconfig->source == GLFW_EGL_CONTEXT_API || ctxconfig->source == GLFW_NATIVE_CONTEXT_API) { - if (!_glfwInitEGL()) return false; - if (!_glfwCreateContextEGL(window, ctxconfig, fbconfig)) return false; - } else if (ctxconfig->source == GLFW_OSMESA_CONTEXT_API) { - if (!_glfwInitOSMesa()) return false; - if (!_glfwCreateContextOSMesa(window, ctxconfig, fbconfig)) return false; - } - return true; -} - int -_glfwPlatformCreateWindow( - _GLFWwindow *window, const _GLFWwndconfig *wndconfig, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig, const GLFWLayerShellConfig *lsc) { +_glfwPlatformCreateWindow(_GLFWwindow *window, const _GLFWwndconfig *wndconfig, const _GLFWfbconfig *fbconfig, const GLFWLayerShellConfig *lsc) { window->wl.layer_shell.config = lsc ? *lsc : (GLFWLayerShellConfig){0}; // Compositors without xdg-decoration such as mutter need client side // decorations, whose titlebar height depends on desktop settings. Wait @@ -1592,11 +1565,9 @@ _glfwPlatformCreateWindow( window->wl.monitorsCount = 0; window->wl.monitorsSize = 1; // looping till window fully created attaches a single pixel buffer to the window, - // this cannot be done once a OpenGL context is created for the window. So first loop - // and only then create the OpenGL context. + // this cannot be done once the GPU driver starts rendering to the window, which it + // does only after the window is created. if (window->wl.visible) loop_till_window_fully_created(window); - debug("Creating OpenGL context and attaching it to window\n"); - if (ctxconfig->client != GLFW_NO_API && !attach_opengl_context_to_window(window, ctxconfig, fbconfig)) return false; return true; } @@ -1620,13 +1591,9 @@ _glfwPlatformDestroyWindow(_GLFWwindow *window) { if (window->wl.org_kde_kwin_blur) org_kde_kwin_blur_release(window->wl.org_kde_kwin_blur); if (window->wl.ext_background_effect_surface_v1) ext_background_effect_surface_v1_destroy(window->wl.ext_background_effect_surface_v1); - if (window->context.destroy) window->context.destroy(window); - csd_free_all_resources(window); if (window->wl.xdg.decoration) zxdg_toplevel_decoration_v1_destroy(window->wl.xdg.decoration); - if (window->wl.native) wl_egl_window_destroy(window->wl.native); - if (window->wl.xdg.toplevel) xdg_toplevel_destroy(window->wl.xdg.toplevel); if (window->wl.xdg.surface) xdg_surface_destroy(window->wl.xdg.surface); @@ -2943,20 +2910,9 @@ _glfwPlatformGetClipboard(GLFWClipboardType clipboard_type, const char *mime_typ } } -EGLenum -_glfwPlatformGetEGLPlatform(EGLint **attribs UNUSED) { - if (_glfw.egl.EXT_platform_base && _glfw.egl.EXT_platform_wayland) return EGL_PLATFORM_WAYLAND_EXT; - else return 0; -} - -EGLNativeDisplayType -_glfwPlatformGetEGLNativeDisplay(void) { - return _glfw.wl.display; -} - -EGLNativeWindowType -_glfwPlatformGetEGLNativeWindow(_GLFWwindow *window) { - return window->wl.native; +void +_glfwPlatformWindowContentsPresented(_GLFWwindow *window) { + _glfwWaylandAfterBufferSwap(window); } void diff --git a/glfw/x11_init.c b/glfw/x11_init.c index c92eb64ae..40c5adfb9 100644 --- a/glfw/x11_init.c +++ b/glfw/x11_init.c @@ -912,17 +912,12 @@ _glfwPlatformTerminate(void) { _glfw.x11.xi.handle = NULL; } - // NOTE: These need to be unloaded after XCloseDisplay, as they register - // cleanup callbacks that get called by that function - _glfwTerminateEGL(); - _glfwTerminateGLX(); - finalizePollData(&_glfw.x11.eventLoopData); } const char * _glfwPlatformGetVersionString(void) { - return _GLFW_VERSION_NUMBER " X11 GLX EGL OSMesa" + return _GLFW_VERSION_NUMBER " X11" #if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK) " clock_gettime" #else diff --git a/glfw/x11_platform.h b/glfw/x11_platform.h index 8a0a7cdf3..821c4c359 100644 --- a/glfw/x11_platform.h +++ b/glfw/x11_platform.h @@ -182,7 +182,6 @@ typedef VkResult(APIENTRY *PFN_vkCreateXcbSurfaceKHR)(VkInstance, const VkXcbSur typedef VkBool32(APIENTRY *PFN_vkGetPhysicalDeviceXcbPresentationSupportKHR)(VkPhysicalDevice, uint32_t, xcb_connection_t *, xcb_visualid_t); #include "posix_thread.h" -#include "glx_context.h" #if defined(__linux__) #include "linux_joystick.h" #else diff --git a/glfw/x11_window.c b/glfw/x11_window.c index 388e79d3d..746fab437 100644 --- a/glfw/x11_window.c +++ b/glfw/x11_window.c @@ -29,6 +29,7 @@ #define _GNU_SOURCE #include "internal.h" +#include #include "math.h" #include "backend_utils.h" #include "linux_notify.h" @@ -2317,44 +2318,34 @@ _glfwPushSelectionToManagerX11(void) { ////////////////////////////////////////////////////////////////////////// int -_glfwPlatformCreateWindow( - _GLFWwindow *window, const _GLFWwndconfig *wndconfig, const _GLFWctxconfig *ctxconfig, const _GLFWfbconfig *fbconfig, const GLFWLayerShellConfig *lsc) { +_glfwPlatformCreateWindow(_GLFWwindow *window, const _GLFWwndconfig *wndconfig, const _GLFWfbconfig *fbconfig UNUSED, const GLFWLayerShellConfig *lsc) { Visual *visual = NULL; - int depth; + int depth = 0; if (lsc) { window->x11.layer_shell.is_active = true; window->x11.layer_shell.config = *lsc; } else window->x11.layer_shell.is_active = false; - if (ctxconfig->client != GLFW_NO_API) { - if (ctxconfig->source == GLFW_NATIVE_CONTEXT_API) { - if (!_glfwInitGLX()) return false; - if (!_glfwChooseVisualGLX(wndconfig, ctxconfig, fbconfig, &visual, &depth)) return false; - } else if (ctxconfig->source == GLFW_EGL_CONTEXT_API) { - if (!_glfwInitEGL()) return false; - if (!_glfwChooseVisualEGL(wndconfig, ctxconfig, fbconfig, &visual, &depth)) return false; - } else if (ctxconfig->source == GLFW_OSMESA_CONTEXT_API) { - if (!_glfwInitOSMesa()) return false; + if (wndconfig->x11.visualID) { + // The visual chosen by the GPU driver + XVisualInfo desired = {.visualid = wndconfig->x11.visualID, .screen = _glfw.x11.screen}; + int count = 0; + XVisualInfo *result = XGetVisualInfo(_glfw.x11.display, VisualIDMask | VisualScreenMask, &desired, &count); + if (!result || !count) { + if (result) XFree(result); + _glfwInputError(GLFW_PLATFORM_ERROR, "X11: Failed to find the visual with id: 0x%lx", wndconfig->x11.visualID); + return false; } - } - - if (!visual) { + visual = result->visual; + depth = result->depth; + XFree(result); + } else { visual = DefaultVisual(_glfw.x11.display, _glfw.x11.screen); depth = DefaultDepth(_glfw.x11.display, _glfw.x11.screen); } if (!createNativeWindow(window, wndconfig, visual, depth)) return false; - if (ctxconfig->client != GLFW_NO_API) { - if (ctxconfig->source == GLFW_NATIVE_CONTEXT_API) { - if (!_glfwCreateContextGLX(window, ctxconfig, fbconfig)) return false; - } else if (ctxconfig->source == GLFW_EGL_CONTEXT_API) { - if (!_glfwCreateContextEGL(window, ctxconfig, fbconfig)) return false; - } else if (ctxconfig->source == GLFW_OSMESA_CONTEXT_API) { - if (!_glfwCreateContextOSMesa(window, ctxconfig, fbconfig)) return false; - } - } - if (window->monitor) { _glfwPlatformShowWindow(window, false); updateWindowMode(window); @@ -2371,8 +2362,6 @@ _glfwPlatformDestroyWindow(_GLFWwindow *window) { if (window->monitor) releaseMonitor(window); - if (window->context.destroy) window->context.destroy(window); - if (window->x11.handle) { XDeleteContext(_glfw.x11.display, window->x11.handle, _glfw.x11.context); XUnmapWindow(_glfw.x11.display, window->x11.handle); @@ -3270,45 +3259,8 @@ _glfwPlatformGetClipboard(GLFWClipboardType clipboard_type, const char *mime_typ getSelectionString(which, atoms, count, write_data, object, true); } -EGLenum -_glfwPlatformGetEGLPlatform(EGLint **attribs) { - if (_glfw.egl.ANGLE_platform_angle) { - int type = 0; - - if (_glfw.egl.ANGLE_platform_angle_opengl) { - if (_glfw.hints.init.angleType == GLFW_ANGLE_PLATFORM_TYPE_OPENGL) type = EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE; - } - - if (_glfw.egl.ANGLE_platform_angle_vulkan) { - if (_glfw.hints.init.angleType == GLFW_ANGLE_PLATFORM_TYPE_VULKAN) type = EGL_PLATFORM_ANGLE_TYPE_VULKAN_ANGLE; - } - - if (type) { - *attribs = calloc(5, sizeof(EGLint)); - (*attribs)[0] = EGL_PLATFORM_ANGLE_TYPE_ANGLE; - (*attribs)[1] = type; - (*attribs)[2] = EGL_PLATFORM_ANGLE_NATIVE_PLATFORM_TYPE_ANGLE; - (*attribs)[3] = EGL_PLATFORM_X11_EXT; - (*attribs)[4] = EGL_NONE; - return EGL_PLATFORM_ANGLE_ANGLE; - } - } - - if (_glfw.egl.EXT_platform_base && _glfw.egl.EXT_platform_x11) return EGL_PLATFORM_X11_EXT; - - return 0; -} - -EGLNativeDisplayType -_glfwPlatformGetEGLNativeDisplay(void) { - return _glfw.x11.display; -} - -EGLNativeWindowType -_glfwPlatformGetEGLNativeWindow(_GLFWwindow *window) { - if (_glfw.egl.platform) return &window->x11.handle; - else return (EGLNativeWindowType)window->x11.handle; -} +void +_glfwPlatformWindowContentsPresented(_GLFWwindow *window UNUSED) {} void _glfwPlatformGetRequiredInstanceExtensions(char **extensions) { @@ -3462,6 +3414,18 @@ glfwGetX11Window(GLFWwindow *handle) { return window->x11.handle; } +GLFWAPI void +glfwX11PushErrorTrap(void) { + _GLFW_REQUIRE_INIT(); + _glfwPushErrorTrapX11(); +} + +GLFWAPI int +glfwX11PopErrorTrap(void) { + _GLFW_REQUIRE_INIT_OR_RETURN(Success); + return _glfwPopErrorTrapX11(); +} + GLFWAPI int glfwGetNativeKeyForName(const char *keyName, bool caseSensitive) { return glfw_xkb_keysym_from_name(keyName, caseSensitive); diff --git a/gpu/api.h b/gpu/api.h index 6130e3e63..32a5241da 100644 --- a/gpu/api.h +++ b/gpu/api.h @@ -33,11 +33,15 @@ // mode and textures bound to texture units. Draw calls use this state. This // is cheap to implement on top of OpenGL and straightforward to record into // command buffers for Vulkan and Metal. +// * Rendering happens into surfaces, created from native windows supplied by +// the windowing system (see GPUNativeWindow). The driver owns everything +// needed to render to and present a surface, such as OpenGL contexts or +// Vulkan swapchains. The windowing system owns only the window itself. // * On APIs where some objects are bound to a context or device queue, such // as framebuffers and vertex array objects in OpenGL, vertex layouts and -// render targets are only valid in the context that was current when they +// render targets are only valid with the surface that was current when they // were created. Textures, buffers and pipelines are shared between all -// contexts. +// surfaces. #pragma once @@ -45,7 +49,7 @@ #include #include -#define KITTY_GPU_API_VERSION 1u +#define KITTY_GPU_API_VERSION 2u #define KITTY_GPU_DRIVER_ENTRY_POINT "kitty_gpu_driver_load" #define GPU_NULL_HANDLE ((uint64_t)0) @@ -54,17 +58,13 @@ typedef uint64_t gpu_buffer_t; typedef uint64_t gpu_pipeline_t; typedef uint64_t gpu_vertex_layout_t; typedef uint64_t gpu_render_target_t; +typedef uint64_t gpu_surface_t; // Initialization {{{ -typedef void (*gpu_proc)(void); -typedef gpu_proc (*gpu_get_proc_address_func)(const char *name); typedef void (*gpu_message_func)(const char *message); typedef struct GPUDriverInitParams { - // Used by drivers that load their API entry points at runtime, such as - // OpenGL. Must be callable once a context is current, see initialize(). - gpu_get_proc_address_func get_proc_address; // Enable extra error checking and debug output bool debug_rendering; // Report a non-fatal error to the user @@ -73,6 +73,18 @@ typedef struct GPUDriverInitParams { gpu_message_func debug_print; // Report an unrecoverable error, must not return gpu_message_func fatal; + // X11: The windowing system installs a process wide X error handler, so + // drivers must not install their own. Instead, to detect errors caused by + // their requests, they call x11_push_error_trap() before making the + // requests and x11_pop_error_trap() after. Errors caused by requests made + // on the display connection while a trap is open are captured by it + // rather than being reported. x11_pop_error_trap() waits for the X server + // to process the requests, if needed, and returns the code of the first + // error caused by them, or zero (Success) if there were none. Traps nest + // and every push must be matched by a pop. Both may only be called on the + // main thread, with surfaces on X11 displays. + void (*x11_push_error_trap)(void); + int (*x11_pop_error_trap)(void); } GPUDriverInitParams; typedef struct GPUCapabilities { @@ -83,6 +95,36 @@ typedef struct GPUCapabilities { } GPUCapabilities; // }}} +// Surfaces {{{ + +typedef enum { + GPU_PLATFORM_X11 = 1, + GPU_PLATFORM_WAYLAND, + GPU_PLATFORM_COCOA, +} GPUPlatform; + +// A native window, or just the native display connection when used with +// choose_native_visual() +typedef struct GPUNativeWindow { + GPUPlatform platform; + void *display; // X11: Display*, Wayland: struct wl_display*, Cocoa: unused + int screen; // X11: the screen number, negative for the default screen, unused on other platforms + uint64_t x11_window; // X11: the Window, unused on other platforms + void *handle; // Wayland: struct wl_surface*, Cocoa: the NSView* to render into, unused on X11 +} GPUNativeWindow; + +typedef struct GPUSurfaceConfig { + // The window is semi-transparent and composited using the alpha channel of its contents + bool transparent; + // Request a framebuffer that supports encoding to sRGB on output + bool srgb; + // macOS: allow rendering on, and automatically switching to, offline or low power GPUs + bool allow_offline_renderers; + // macOS: render at the full resolution of high DPI (retina) displays + bool high_resolution; +} GPUSurfaceConfig; +// }}} + // Textures {{{ typedef enum { @@ -211,9 +253,9 @@ typedef struct GPUDriverAPI { uint32_t api_version; // Lifecycle {{{ - // Called once, when the first context or surface the driver will render - // to is current. Must be called before any other function except - // destroy() and last_error(). + // Called once, when the first surface has been created and made current. + // Must be called before any other function except destroy(), + // last_error() and the surface functions. bool (*initialize)(void *driver); void (*destroy)(void *driver); // A description of the last error, never NULL @@ -307,6 +349,43 @@ typedef struct GPUDriverAPI { uint32_t instance_divisor); // }}} + // Surfaces {{{ + // Some platforms, such as X11, require the visual of a window to be + // chosen before the window is created. native must describe only the + // display. Sets visual_id to the id of the visual the window must use, + // or zero if the driver has no preference. + bool (*choose_native_visual)(void *driver, const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint64_t *visual_id); + // Create a surface to render into the native window. width and height + // are the size of the window framebuffer in pixels. Does not change the + // current surface. + gpu_surface_t (*surface_create)(void *driver, const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint32_t width, uint32_t height); + // Destroy a surface, must be called before its native window is destroyed + void (*surface_destroy)(void *driver, gpu_surface_t surface); + // Make a surface current, all subsequent rendering goes to it. + // GPU_NULL_HANDLE for no surface. + bool (*make_surface_current)(void *driver, gpu_surface_t surface); + gpu_surface_t (*get_current_surface)(void *driver); + // Inform the driver that the framebuffer of the native window was resized + void (*surface_resize)(void *driver, gpu_surface_t surface, uint32_t width, uint32_t height); + // Present the rendered contents of the surface on screen + bool (*surface_present)(void *driver, gpu_surface_t surface); + // Set the number of display refreshes to wait for when presenting the + // surface, zero to present immediately. The surface must be current. + void (*surface_set_swap_interval)(void *driver, gpu_surface_t surface, int interval); + // Inform the driver that the geometry or screen of the native window + // changed, needed on platforms such as Cocoa where the driver must update + // the drawable it renders into + void (*surface_native_changed)(void *driver, gpu_surface_t surface); + // Recreate the drawable of the surface, used to recover when the platform + // invalidates it. Makes the surface current. Per surface state, such as + // vertex layouts and render targets must be recreated. + bool (*surface_recreate)(void *driver, gpu_surface_t surface); + // Destroy all surfaces and release all connections to the windowing + // system. Must be called before the windowing system is shut down. + // After this only destroy() may be called. + void (*release_native_resources)(void *driver); + // }}} + // Render targets {{{ // Create a render target that draws into the specified texture. Does not // change the current render target. Use render_target_status() to check diff --git a/gpu/opengl/driver.c b/gpu/opengl/driver.c index 9965929ed..707bd60c9 100644 --- a/gpu/opengl/driver.c +++ b/gpu/opengl/driver.c @@ -8,6 +8,7 @@ // The OpenGL implementation of the kitty GPU driver API, see ../api.h #include "../api.h" +#include "platform.h" #include "version.h" #include "gl-wrapper.h" #include @@ -49,6 +50,8 @@ typedef struct Pipeline { typedef struct Driver { GPUDriverInitParams params; + const GLPlatform *platform; + GLSurface *current_surface; bool initialized, supports_srgb_output; int gl_version; GLint max_texture_size, max_array_texture_layers; @@ -64,6 +67,7 @@ static Driver *the_driver = NULL; #define AS_TEXTURE(handle) ((Texture *)(uintptr_t)(handle)) #define AS_BUFFER(handle) ((Buffer *)(uintptr_t)(handle)) #define AS_PIPELINE(handle) ((Pipeline *)(uintptr_t)(handle)) +#define AS_SURFACE(handle) ((GLSurface *)(uintptr_t)(handle)) #define AS_HANDLE(ptr) ((uint64_t)(uintptr_t)(ptr)) // Framebuffers and vertex array objects need no extra state, so their handles are the OpenGL names #define AS_GL_NAME(handle) ((GLuint)(handle)) @@ -153,7 +157,11 @@ static bool initialize(void *driver) { Driver *d = driver; if (d->initialized) return true; - d->gl_version = gladLoadGL((GLADloadfunc)d->params.get_proc_address); + if (!d->platform || !d->current_surface) { + set_error(d, "The OpenGL driver must have a current surface before it can be initialized"); + return false; + } + d->gl_version = gladLoadGL((GLADloadfunc)d->platform->get_proc_address); if (!d->gl_version) { set_error(d, "Loading the OpenGL library failed"); return false; @@ -201,8 +209,11 @@ initialize(void *driver) { return true; } +static void release_native_resources(void *driver); + static void destroy(void *driver) { + release_native_resources(driver); if (the_driver == driver) the_driver = NULL; free(driver); } @@ -836,6 +847,196 @@ vertex_layout_set_attribute( } // }}} +// Surfaces {{{ +bool +gl_extension_in_string(const char *name, const char *extensions) { + const size_t len = strlen(name); + for (const char *start = extensions;;) { + const char *where = strstr(start, name); + if (!where) return false; + const char *terminator = where + len; + if ((where == start || *(where - 1) == ' ') && (*terminator == ' ' || *terminator == '\0')) return true; + start = terminator; + } +} + +static void host_set_error(const char *fmt, ...) __attribute__((format(printf, 1, 2))); + +static void +host_set_error(const char *fmt, ...) { + if (!the_driver) return; + va_list ap; + va_start(ap, fmt); + vsnprintf(the_driver->last_error, sizeof(the_driver->last_error), fmt, ap); + va_end(ap); +} + +static void host_log_error(const char *fmt, ...) __attribute__((format(printf, 1, 2))); + +static void +host_log_error(const char *fmt, ...) { + if (!the_driver) return; + char buf[4096]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + the_driver->params.log_error(buf); +} + +static void host_debug(const char *fmt, ...) __attribute__((format(printf, 1, 2))); + +static void +host_debug(const char *fmt, ...) { + if (!the_driver || !the_driver->params.debug_rendering) return; + char buf[4096]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + the_driver->params.debug_print(buf); +} + +static void +host_x11_push_error_trap(void) { + if (the_driver && the_driver->params.x11_push_error_trap) the_driver->params.x11_push_error_trap(); +} + +static int +host_x11_pop_error_trap(void) { + if (the_driver && the_driver->params.x11_pop_error_trap) return the_driver->params.x11_pop_error_trap(); + return 0; +} + +static const GLPlatformHost platform_host = { + .set_error = host_set_error, + .log_error = host_log_error, + .debug = host_debug, + .x11_push_error_trap = host_x11_push_error_trap, + .x11_pop_error_trap = host_x11_pop_error_trap, +}; + +// Select the platform API used to create contexts for windows of the +// specified type. All windows must be of the same type. +static bool +ensure_platform(Driver *d, GPUPlatform type) { + const GLPlatform *p = NULL; + switch (type) { +#ifdef __APPLE__ + case GPU_PLATFORM_COCOA: p = nsgl_platform(&platform_host); break; + case GPU_PLATFORM_X11: + case GPU_PLATFORM_WAYLAND: break; +#else + case GPU_PLATFORM_X11: p = glx_platform(&platform_host); break; + case GPU_PLATFORM_WAYLAND: p = egl_platform(&platform_host); break; + case GPU_PLATFORM_COCOA: break; +#endif + } + if (!p) { + set_error(d, "The OpenGL driver does not support windows of type: %d on this platform", (int)type); + return false; + } + if (d->platform && d->platform != p) { + set_error(d, "The OpenGL driver cannot render to windows using both %s and %s", d->platform->name, p->name); + return false; + } + d->platform = p; + return true; +} + +static bool +choose_native_visual(void *driver, const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint64_t *visual_id) { + Driver *d = driver; + *visual_id = 0; + if (!ensure_platform(d, native->platform)) return false; + return d->platform->choose_native_visual(native, config, visual_id); +} + +static gpu_surface_t +surface_create(void *driver, const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint32_t width, uint32_t height) { + Driver *d = driver; + if (!ensure_platform(d, native->platform)) return GPU_NULL_HANDLE; + GLSurface *s = d->platform->surface_create(native, config, width, height); + if (s) host_debug("Created %s OpenGL context for window of size: %ux%u", d->platform->name, width, height); + return AS_HANDLE(s); +} + +static void +surface_destroy(void *driver, gpu_surface_t surface) { + Driver *d = driver; + GLSurface *s = AS_SURFACE(surface); + if (!s || !d->platform) return; + if (d->current_surface == s) { + d->platform->make_current(NULL); + d->current_surface = NULL; + } + d->platform->surface_destroy(s); +} + +static bool +make_surface_current(void *driver, gpu_surface_t surface) { + Driver *d = driver; + GLSurface *s = AS_SURFACE(surface); + if (!d->platform) { + if (!s) return true; + set_error(d, "Cannot make a surface current before any surface is created"); + return false; + } + if (!d->platform->make_current(s)) return false; + d->current_surface = s; + return true; +} + +static gpu_surface_t +get_current_surface(void *driver) { + return AS_HANDLE(((Driver *)driver)->current_surface); +} + +static void +surface_resize(void *driver, gpu_surface_t surface, uint32_t width, uint32_t height) { + Driver *d = driver; + if (surface && d->platform) d->platform->surface_resize(AS_SURFACE(surface), width, height); +} + +static bool +surface_present(void *driver, gpu_surface_t surface) { + Driver *d = driver; + if (!surface || !d->platform) return false; + return d->platform->present(AS_SURFACE(surface)); +} + +static void +surface_set_swap_interval(void *driver, gpu_surface_t surface, int interval) { + Driver *d = driver; + if (surface && d->platform) d->platform->set_swap_interval(AS_SURFACE(surface), interval); +} + +static void +surface_native_changed(void *driver, gpu_surface_t surface) { + Driver *d = driver; + if (surface && d->platform) d->platform->native_changed(AS_SURFACE(surface)); +} + +static bool +surface_recreate(void *driver, gpu_surface_t surface) { + Driver *d = driver; + if (!surface || !d->platform) return false; + if (!d->platform->recreate(AS_SURFACE(surface))) return false; + d->current_surface = AS_SURFACE(surface); + return true; +} + +static void +release_native_resources(void *driver) { + Driver *d = driver; + if (!d->platform) return; + d->platform->make_current(NULL); + d->current_surface = NULL; + d->platform->terminate(); + d->platform = NULL; +} +// }}} + // Render targets {{{ static const char * framebuffer_status_string(GLenum status) { @@ -977,7 +1178,7 @@ kitty_gpu_driver_load(uint32_t api_version, const GPUDriverInitParams *params, G snprintf(errbuf, errbuf_size, "The OpenGL driver supports GPU API version %u but version %u was requested", KITTY_GPU_API_VERSION, api_version); return false; } - if (!params->get_proc_address || !params->log_error || !params->fatal || !params->debug_print) { + if (!params->log_error || !params->fatal || !params->debug_print) { snprintf(errbuf, errbuf_size, "The OpenGL driver was not passed all required callbacks"); return false; } @@ -1035,6 +1236,18 @@ kitty_gpu_driver_load(uint32_t api_version, const GPUDriverInitParams *params, G F(bind_vertex_layout), F(vertex_layout_set_attribute), + F(choose_native_visual), + F(surface_create), + F(surface_destroy), + F(make_surface_current), + F(get_current_surface), + F(surface_resize), + F(surface_present), + F(surface_set_swap_interval), + F(surface_native_changed), + F(surface_recreate), + F(release_native_resources), + F(render_target_create), F(render_target_destroy), F(set_render_target), diff --git a/gpu/opengl/egl.c b/gpu/opengl/egl.c new file mode 100644 index 000000000..f4ba0ac66 --- /dev/null +++ b/gpu/opengl/egl.c @@ -0,0 +1,470 @@ +/* + * egl.c + * Copyright (C) 2026 Kovid Goyal + * Based on egl_context.c from GLFW, Copyright (c) 2002-2006 Marcus Geelnard + * and (c) 2006-2019 Camilla Löwy + * + * Distributed under terms of the GPL3 license. + */ + +// OpenGL contexts for Wayland windows, created using EGL. All libraries are +// loaded at runtime, so that the driver has no link time dependencies. + +#include "platform.h" +#include "version.h" +#include +#include +#include + +#define EGL_SUCCESS 0x3000 +#define EGL_NOT_INITIALIZED 0x3001 +#define EGL_BAD_ACCESS 0x3002 +#define EGL_BAD_ALLOC 0x3003 +#define EGL_BAD_ATTRIBUTE 0x3004 +#define EGL_BAD_CONFIG 0x3005 +#define EGL_BAD_CONTEXT 0x3006 +#define EGL_BAD_CURRENT_SURFACE 0x3007 +#define EGL_BAD_DISPLAY 0x3008 +#define EGL_BAD_MATCH 0x3009 +#define EGL_BAD_NATIVE_PIXMAP 0x300a +#define EGL_BAD_NATIVE_WINDOW 0x300b +#define EGL_BAD_PARAMETER 0x300c +#define EGL_BAD_SURFACE 0x300d +#define EGL_CONTEXT_LOST 0x300e +#define EGL_COLOR_BUFFER_TYPE 0x303f +#define EGL_RGB_BUFFER 0x308e +#define EGL_SURFACE_TYPE 0x3033 +#define EGL_WINDOW_BIT 0x0004 +#define EGL_RENDERABLE_TYPE 0x3040 +#define EGL_OPENGL_BIT 0x0008 +#define EGL_ALPHA_SIZE 0x3021 +#define EGL_BLUE_SIZE 0x3022 +#define EGL_GREEN_SIZE 0x3023 +#define EGL_RED_SIZE 0x3024 +#define EGL_OPENGL_API 0x30a2 +#define EGL_NONE 0x3038 +#define EGL_EXTENSIONS 0x3055 +#define EGL_MIN_SWAP_INTERVAL 0x303B +#define EGL_NO_SURFACE ((EGLSurface)0) +#define EGL_NO_DISPLAY ((EGLDisplay)0) +#define EGL_NO_CONTEXT ((EGLContext)0) +#define EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR 0x00000002 +#define EGL_CONTEXT_MAJOR_VERSION_KHR 0x3098 +#define EGL_CONTEXT_MINOR_VERSION_KHR 0x30fb +#define EGL_CONTEXT_FLAGS_KHR 0x30fc +#define EGL_GL_COLORSPACE_KHR 0x309d +#define EGL_GL_COLORSPACE_SRGB_KHR 0x3089 +#define EGL_PLATFORM_WAYLAND_EXT 0x31d8 + +typedef int EGLint; +typedef unsigned int EGLBoolean; +typedef unsigned int EGLenum; +typedef void *EGLConfig; +typedef void *EGLContext; +typedef void *EGLDisplay; +typedef void *EGLSurface; +typedef void *EGLNativeDisplayType; +typedef void *EGLNativeWindowType; + +struct wl_surface; +struct wl_egl_window; + +static struct { + void *handle, *wl_egl_handle, *client; + EGLenum platform; + EGLDisplay display; + EGLint major, minor; + bool initialized, KHR_create_context, KHR_gl_colorspace, KHR_get_all_proc_addresses, EXT_platform_base, EXT_platform_wayland; + + EGLBoolean (*GetConfigAttrib)(EGLDisplay, EGLConfig, EGLint, EGLint *); + EGLBoolean (*ChooseConfig)(EGLDisplay, EGLint const *, EGLConfig *, EGLint, EGLint *); + EGLDisplay (*GetDisplay)(EGLNativeDisplayType); + EGLint (*GetError)(void); + EGLBoolean (*Initialize)(EGLDisplay, EGLint *, EGLint *); + EGLBoolean (*Terminate)(EGLDisplay); + EGLBoolean (*BindAPI)(EGLenum); + EGLContext (*CreateContext)(EGLDisplay, EGLConfig, EGLContext, const EGLint *); + EGLBoolean (*DestroySurface)(EGLDisplay, EGLSurface); + EGLBoolean (*DestroyContext)(EGLDisplay, EGLContext); + EGLSurface (*CreateWindowSurface)(EGLDisplay, EGLConfig, EGLNativeWindowType, const EGLint *); + EGLBoolean (*MakeCurrent)(EGLDisplay, EGLSurface, EGLSurface, EGLContext); + EGLBoolean (*SwapBuffers)(EGLDisplay, EGLSurface); + EGLBoolean (*SwapInterval)(EGLDisplay, EGLint); + const char *(*QueryString)(EGLDisplay, EGLint); + gl_proc (*GetProcAddress)(const char *); + EGLDisplay (*GetPlatformDisplayEXT)(EGLenum, void *, const EGLint *); + EGLSurface (*CreatePlatformWindowSurfaceEXT)(EGLDisplay, EGLConfig, void *, const EGLint *); + + struct wl_egl_window *(*wl_egl_window_create)(struct wl_surface *, int, int); + void (*wl_egl_window_destroy)(struct wl_egl_window *); + void (*wl_egl_window_resize)(struct wl_egl_window *, int, int, int, int); +} egl = {0}; + +struct GLSurface { + EGLConfig config; + EGLContext context; + EGLSurface surface; + struct wl_egl_window *native; + GLSurface *next; +}; + +static const GLPlatformHost *host = NULL; +static GLSurface *all_surfaces = NULL; + +static const char * +egl_error_string(EGLint error) { + switch (error) { + case EGL_SUCCESS: return "Success"; + case EGL_NOT_INITIALIZED: return "EGL is not or could not be initialized"; + case EGL_BAD_ACCESS: return "EGL cannot access a requested resource"; + case EGL_BAD_ALLOC: return "EGL failed to allocate resources for the requested operation"; + case EGL_BAD_ATTRIBUTE: return "An unrecognized attribute or attribute value was passed in the attribute list"; + case EGL_BAD_CONTEXT: return "An EGLContext argument does not name a valid EGL rendering context"; + case EGL_BAD_CONFIG: return "An EGLConfig argument does not name a valid EGL frame buffer configuration"; + case EGL_BAD_CURRENT_SURFACE: return "The current surface of the calling thread is a window, pixel buffer or pixmap that is no longer valid"; + case EGL_BAD_DISPLAY: return "An EGLDisplay argument does not name a valid EGL display connection"; + case EGL_BAD_SURFACE: return "An EGLSurface argument does not name a valid surface configured for GL rendering"; + case EGL_BAD_MATCH: return "Arguments are inconsistent"; + case EGL_BAD_PARAMETER: return "One or more argument values are invalid"; + case EGL_BAD_NATIVE_PIXMAP: return "A NativePixmapType argument does not refer to a valid native pixmap"; + case EGL_BAD_NATIVE_WINDOW: return "A NativeWindowType argument does not refer to a valid native window"; + case EGL_CONTEXT_LOST: return "The application must destroy all contexts and reinitialise"; + default: return "ERROR: UNKNOWN EGL ERROR"; + } +} + +#define LOAD(lib, dest, name) \ + do { \ + *(void **)&(dest) = dlsym(lib, name); \ + if (!(dest)) { \ + host->set_error("EGL: Failed to load required entry point: %s", name); \ + return false; \ + } \ + } while (0) + +static bool +load_libraries(void) { + if (egl.handle) return true; +#ifdef _GLFW_EGL_LIBRARY + const char *soname = _GLFW_EGL_LIBRARY; +#else + const char *soname = "libEGL.so.1"; +#endif + egl.handle = dlopen(soname, RTLD_LAZY | RTLD_LOCAL); + if (!egl.handle) { + host->set_error("EGL: Library not found: %s", soname); + return false; + } + egl.wl_egl_handle = dlopen("libwayland-egl.so.1", RTLD_LAZY | RTLD_LOCAL); + if (!egl.wl_egl_handle) { + host->set_error("Wayland: Failed to open libwayland-egl"); + return false; + } + LOAD(egl.wl_egl_handle, egl.wl_egl_window_create, "wl_egl_window_create"); + LOAD(egl.wl_egl_handle, egl.wl_egl_window_destroy, "wl_egl_window_destroy"); + LOAD(egl.wl_egl_handle, egl.wl_egl_window_resize, "wl_egl_window_resize"); + LOAD(egl.handle, egl.GetConfigAttrib, "eglGetConfigAttrib"); + LOAD(egl.handle, egl.ChooseConfig, "eglChooseConfig"); + LOAD(egl.handle, egl.GetDisplay, "eglGetDisplay"); + LOAD(egl.handle, egl.GetError, "eglGetError"); + LOAD(egl.handle, egl.Initialize, "eglInitialize"); + LOAD(egl.handle, egl.Terminate, "eglTerminate"); + LOAD(egl.handle, egl.BindAPI, "eglBindAPI"); + LOAD(egl.handle, egl.CreateContext, "eglCreateContext"); + LOAD(egl.handle, egl.DestroySurface, "eglDestroySurface"); + LOAD(egl.handle, egl.DestroyContext, "eglDestroyContext"); + LOAD(egl.handle, egl.CreateWindowSurface, "eglCreateWindowSurface"); + LOAD(egl.handle, egl.MakeCurrent, "eglMakeCurrent"); + LOAD(egl.handle, egl.SwapBuffers, "eglSwapBuffers"); + LOAD(egl.handle, egl.SwapInterval, "eglSwapInterval"); + LOAD(egl.handle, egl.QueryString, "eglQueryString"); + LOAD(egl.handle, egl.GetProcAddress, "eglGetProcAddress"); + return true; +} +#undef LOAD + +static bool +extension_supported(const char *name) { + const char *extensions = egl.QueryString(egl.display, EGL_EXTENSIONS); + return extensions && gl_extension_in_string(name, extensions); +} + +static bool +initialize(void *wl_display) { + if (egl.initialized) return true; + if (!load_libraries()) return false; + const char *extensions = egl.QueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); + if (extensions && egl.GetError() == EGL_SUCCESS) { + egl.EXT_platform_base = gl_extension_in_string("EGL_EXT_platform_base", extensions); + egl.EXT_platform_wayland = gl_extension_in_string("EGL_EXT_platform_wayland", extensions); + } + if (egl.EXT_platform_base) { + // Converting between function pointer types is allowed, unlike + // between function and object pointers + gl_proc p = egl.GetProcAddress("eglGetPlatformDisplayEXT"); + memcpy(&egl.GetPlatformDisplayEXT, &p, sizeof(p)); + p = egl.GetProcAddress("eglCreatePlatformWindowSurfaceEXT"); + memcpy(&egl.CreatePlatformWindowSurfaceEXT, &p, sizeof(p)); + } + egl.platform = + egl.EXT_platform_base && egl.EXT_platform_wayland && egl.GetPlatformDisplayEXT && egl.CreatePlatformWindowSurfaceEXT ? EGL_PLATFORM_WAYLAND_EXT : 0; + egl.display = EGL_NO_DISPLAY; + if (egl.platform) egl.display = egl.GetPlatformDisplayEXT(egl.platform, wl_display, NULL); + if (egl.display == EGL_NO_DISPLAY) egl.display = egl.GetDisplay(wl_display); + EGLint egl_err; + if (egl.display == EGL_NO_DISPLAY && (egl_err = egl.GetError()) != EGL_SUCCESS) { + host->set_error("EGL: Failed to get EGL display: %s", egl_error_string(egl_err)); + return false; + } + if (!egl.Initialize(egl.display, &egl.major, &egl.minor)) { + host->set_error( + "EGL: Failed to initialize EGL: %s display_present: %d egl_platform_present: %d", + egl_error_string(egl.GetError()), + egl.display != EGL_NO_DISPLAY, + egl.platform != 0); + egl.display = EGL_NO_DISPLAY; + return false; + } + egl.KHR_create_context = extension_supported("EGL_KHR_create_context"); + egl.KHR_gl_colorspace = extension_supported("EGL_KHR_gl_colorspace"); + egl.KHR_get_all_proc_addresses = extension_supported("EGL_KHR_get_all_proc_addresses"); + if (!egl.KHR_get_all_proc_addresses) { + // eglGetProcAddress() may not return core functions, so they must be + // looked up in the client library instead + egl.client = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL); + if (!egl.client) { + host->set_error("EGL: Failed to load client library"); + return false; + } + } + egl.initialized = true; + return true; +} + +static bool +choose_config(const GPUSurfaceConfig *config, EGLConfig *result) { + (void)config; // Wayland composites using the alpha channel of every buffer, so no special config is needed for transparency + EGLConfig configs[512]; + EGLint native_count = 0; + const EGLint attributes[] = { + EGL_COLOR_BUFFER_TYPE, + EGL_RGB_BUFFER, + EGL_SURFACE_TYPE, + EGL_WINDOW_BIT, + EGL_RENDERABLE_TYPE, + EGL_OPENGL_BIT, + EGL_RED_SIZE, + 8, + EGL_GREEN_SIZE, + 8, + EGL_BLUE_SIZE, + 8, + EGL_ALPHA_SIZE, + 8, + EGL_NONE, + EGL_NONE, + }; + if (!egl.ChooseConfig(egl.display, attributes, configs, sizeof(configs) / sizeof(configs[0]), &native_count)) { + host->set_error("EGL: eglChooseConfig failed"); + return false; + } + if (!native_count) { + host->set_error("EGL: No EGLConfigs returned"); + return false; + } + *result = configs[0]; + return true; +} + +static bool +choose_native_visual(const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint64_t *visual_id) { + (void)native; + (void)config; + *visual_id = 0; + return true; +} + +static bool +make_current(GLSurface *s) { + if (!egl.initialized) return true; + if (s) { + if (!egl.MakeCurrent(egl.display, s->surface, s->surface, s->context)) { + host->set_error("EGL: Failed to make context current: %s", egl_error_string(egl.GetError())); + return false; + } + } else { + if (!egl.MakeCurrent(egl.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) { + host->set_error("EGL: Failed to clear current context: %s", egl_error_string(egl.GetError())); + return false; + } + } + return true; +} + +static void +surface_destroy(GLSurface *s) { + if (!s) return; + if (s->surface) egl.DestroySurface(egl.display, s->surface); + if (s->context) egl.DestroyContext(egl.display, s->context); + if (s->native) egl.wl_egl_window_destroy(s->native); + for (GLSurface **p = &all_surfaces; *p; p = &(*p)->next) { + if (*p == s) { + *p = s->next; + break; + } + } + free(s); +} + +static GLSurface * +surface_create(const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint32_t width, uint32_t height) { + if (native->platform != GPU_PLATFORM_WAYLAND || !native->handle) { + host->set_error("EGL: Only Wayland windows are supported"); + return NULL; + } + if (!initialize(native->display)) return NULL; + GLSurface *s = calloc(1, sizeof(GLSurface)); + if (!s) { + host->set_error("EGL: Out of memory"); + return NULL; + } + s->next = all_surfaces; + all_surfaces = s; + if (!choose_config(config, &s->config)) { + surface_destroy(s); + return NULL; + } + if (!egl.BindAPI(EGL_OPENGL_API)) { + host->set_error("EGL: Failed to bind OpenGL: %s", egl_error_string(egl.GetError())); + surface_destroy(s); + return NULL; + } + EGLint attribs[16]; + int index = 0; +#define set_attrib(a, v) \ + { \ + attribs[index++] = a; \ + attribs[index++] = v; \ + } + if (egl.KHR_create_context) { + set_attrib(EGL_CONTEXT_MAJOR_VERSION_KHR, OPENGL_REQUIRED_VERSION_MAJOR); + set_attrib(EGL_CONTEXT_MINOR_VERSION_KHR, OPENGL_REQUIRED_VERSION_MINOR); + set_attrib(EGL_CONTEXT_FLAGS_KHR, EGL_CONTEXT_OPENGL_FORWARD_COMPATIBLE_BIT_KHR); + } + set_attrib(EGL_NONE, EGL_NONE); + // Share objects with any existing context + EGLContext share = s->next ? s->next->context : EGL_NO_CONTEXT; + s->context = egl.CreateContext(egl.display, s->config, share, attribs); + if (s->context == EGL_NO_CONTEXT) { + host->set_error( + "EGL: Failed to create context: %s. kitty requires working OpenGL %d.%d drivers.", + egl_error_string(egl.GetError()), + OPENGL_REQUIRED_VERSION_MAJOR, + OPENGL_REQUIRED_VERSION_MINOR); + surface_destroy(s); + return NULL; + } + index = 0; + if (config->srgb && egl.KHR_gl_colorspace) set_attrib(EGL_GL_COLORSPACE_KHR, EGL_GL_COLORSPACE_SRGB_KHR); + // EGL_PRESENT_OPAQUE_EXT is not used because it prevents transparency from + // working on NVIDIA drivers under Wayland https://github.com/kovidgoyal/kitty/issues/5479 + set_attrib(EGL_NONE, EGL_NONE); +#undef set_attrib + s->native = egl.wl_egl_window_create((struct wl_surface *)native->handle, (int)width, (int)height); + if (!s->native) { + host->set_error("Wayland: Failed to create EGL window"); + surface_destroy(s); + return NULL; + } + if (egl.platform) s->surface = egl.CreatePlatformWindowSurfaceEXT(egl.display, s->config, s->native, attribs); + else s->surface = egl.CreateWindowSurface(egl.display, s->config, (EGLNativeWindowType)s->native, attribs); + if (s->surface == EGL_NO_SURFACE) { + host->set_error("EGL: Failed to create window surface: %s", egl_error_string(egl.GetError())); + surface_destroy(s); + return NULL; + } + EGLint min_interval = 0; + if (!egl.GetConfigAttrib(egl.display, s->config, EGL_MIN_SWAP_INTERVAL, &min_interval)) { + host->log_error("EGL: could not check for non-blocking buffer swap with error: %s", egl_error_string(egl.GetError())); + } else if (min_interval > 0) { + host->log_error("EGL: non-blocking swap buffers not available, minimum swap interval is: %d", min_interval); + } + return s; +} + +static void +surface_resize(GLSurface *s, uint32_t width, uint32_t height) { + // Does not actually resize the buffer until the next draw call or buffer state query + egl.wl_egl_window_resize(s->native, (int)width, (int)height, 0, 0); +} + +static bool +present(GLSurface *s) { + if (!egl.SwapBuffers(egl.display, s->surface)) { + host->set_error("EGL: Failed to swap buffers: %s", egl_error_string(egl.GetError())); + return false; + } + return true; +} + +static void +set_swap_interval(GLSurface *s, int interval) { + (void)s; + egl.SwapInterval(egl.display, interval); +} + +static void +native_changed(GLSurface *s) { + (void)s; +} + +static bool +recreate(GLSurface *s) { + (void)s; + host->set_error("EGL: Recreating surfaces is not supported"); + return false; +} + +static gl_proc +get_proc_address(const char *name) { + if (egl.client) { + gl_proc ans = NULL; + *(void **)&ans = dlsym(egl.client, name); + if (ans) return ans; + } + return egl.GetProcAddress(name); +} + +static void +terminate(void) { + while (all_surfaces) surface_destroy(all_surfaces); + // Must be called before disconnecting from the Wayland display since + // eglTerminate sends Wayland protocol requests. The libraries are never + // unloaded as the Wayland message format tables they contain must remain + // mapped while the Wayland event queue is drained during disconnection. + if (egl.display) { + egl.Terminate(egl.display); + egl.display = EGL_NO_DISPLAY; + } + egl.initialized = false; +} + +const GLPlatform * +egl_platform(const GLPlatformHost *h) { + static const GLPlatform ans = { + .name = "EGL", + .choose_native_visual = choose_native_visual, + .surface_create = surface_create, + .surface_destroy = surface_destroy, + .make_current = make_current, + .surface_resize = surface_resize, + .present = present, + .set_swap_interval = set_swap_interval, + .native_changed = native_changed, + .recreate = recreate, + .get_proc_address = get_proc_address, + .terminate = terminate, + }; + host = h; + return &ans; +} diff --git a/gpu/opengl/glx.c b/gpu/opengl/glx.c new file mode 100644 index 000000000..e5bace8fb --- /dev/null +++ b/gpu/opengl/glx.c @@ -0,0 +1,501 @@ +/* + * glx.c + * Copyright (C) 2026 Kovid Goyal + * Based on glx_context.c from GLFW, Copyright (c) 2002-2006 Marcus Geelnard + * and (c) 2006-2019 Camilla Löwy + * + * Distributed under terms of the GPL3 license. + */ + +// OpenGL contexts for X11 windows, created using GLX. All libraries are +// loaded at runtime, so that the driver has no link time dependencies. + +#include "platform.h" +#include "version.h" +#include +#include +#include +#include +#include +#include +#include + +#define GLX_VENDOR 1 +#define GLX_RGBA_TYPE 0x8014 +#define GLX_DOUBLEBUFFER 5 +#define GLX_RED_SIZE 8 +#define GLX_GREEN_SIZE 9 +#define GLX_BLUE_SIZE 10 +#define GLX_ALPHA_SIZE 11 +#define GLX_DEPTH_SIZE 12 +#define GLX_STENCIL_SIZE 13 +#define GLX_DRAWABLE_TYPE 0x8010 +#define GLX_VISUAL_ID 0x800b +#define GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20b2 +#define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002 +#define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 +#define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 +#define GLX_CONTEXT_FLAGS_ARB 0x2094 + +typedef XID GLXWindow; +typedef XID GLXDrawable; +typedef struct __GLXFBConfig *GLXFBConfig; +typedef struct __GLXcontext *GLXContext; + +static struct { + void *handle, *x11_handle, *xrender_handle; + Display *display; + int screen; + int major, minor, event_base, error_base; + bool initialized, xrender_available; + bool SGI_swap_control, EXT_swap_control, MESA_swap_control, ARB_framebuffer_sRGB, EXT_framebuffer_sRGB, ARB_create_context; + // The cached result of choose_fb_config() + struct { + bool valid, transparent, srgb; + GLXFBConfig config; + } chosen; + + GLXFBConfig *(*GetFBConfigs)(Display *, int, int *); + int (*GetFBConfigAttrib)(Display *, GLXFBConfig, int, int *); + GLXFBConfig *(*ChooseFBConfig)(Display *, int, const int *, int *); + const char *(*GetClientString)(Display *, int); + Bool (*QueryExtension)(Display *, int *, int *); + Bool (*QueryVersion)(Display *, int *, int *); + void (*DestroyContext)(Display *, GLXContext); + Bool (*MakeCurrent)(Display *, GLXDrawable, GLXContext); + void (*SwapBuffers)(Display *, GLXDrawable); + const char *(*QueryExtensionsString)(Display *, int); + GLXContext (*CreateNewContext)(Display *, GLXFBConfig, int, GLXContext, Bool); + XVisualInfo *(*GetVisualFromFBConfig)(Display *, GLXFBConfig); + GLXWindow (*CreateWindow)(Display *, GLXFBConfig, Window, const int *); + void (*DestroyWindow)(Display *, GLXWindow); + gl_proc (*GetProcAddress)(const unsigned char *); + gl_proc (*GetProcAddressARB)(const unsigned char *); + int (*SwapIntervalSGI)(int); + void (*SwapIntervalEXT)(Display *, GLXDrawable, int); + int (*SwapIntervalMESA)(int); + GLXContext (*CreateContextAttribsARB)(Display *, GLXFBConfig, GLXContext, Bool, const int *); + + int (*XFree)(void *); + int (*XGetErrorText)(Display *, int, char *, int); + int (*XDefaultScreen)(Display *); + Bool (*XRenderQueryExtension)(Display *, int *, int *); + XRenderPictFormat *(*XRenderFindVisualFormat)(Display *, const Visual *); +} glx = {0}; + +struct GLSurface { + GLXContext context; + GLXWindow window; + GLSurface *next; +}; + +static const GLPlatformHost *host = NULL; +static GLSurface *all_surfaces = NULL; + +#define LOAD(lib, dest, name) \ + do { \ + *(void **)&(dest) = dlsym(lib, name); \ + if (!(dest)) { \ + host->set_error("GLX: Failed to load required entry point: %s", name); \ + return false; \ + } \ + } while (0) + +static void * +open_first(const char *const *sonames) { + for (size_t i = 0; sonames[i]; i++) { + void *ans = dlopen(sonames[i], RTLD_LAZY | RTLD_LOCAL); + if (ans) return ans; + } + return NULL; +} + +static bool +load_libraries(void) { + if (glx.handle) return true; + static const char *const gl_sonames[] = { +#if defined(_GLFW_GLX_LIBRARY) + _GLFW_GLX_LIBRARY, +#endif + "libGL.so.1", + "libGL.so", + NULL}; + static const char *const x11_sonames[] = {"libX11.so.6", "libX11.so", NULL}; + static const char *const xrender_sonames[] = {"libXrender.so.1", "libXrender.so", NULL}; + glx.x11_handle = open_first(x11_sonames); + if (!glx.x11_handle) { + host->set_error("GLX: Failed to load libX11"); + return false; + } + LOAD(glx.x11_handle, glx.XFree, "XFree"); + LOAD(glx.x11_handle, glx.XGetErrorText, "XGetErrorText"); + LOAD(glx.x11_handle, glx.XDefaultScreen, "XDefaultScreen"); + glx.xrender_handle = open_first(xrender_sonames); + if (glx.xrender_handle) { + LOAD(glx.xrender_handle, glx.XRenderQueryExtension, "XRenderQueryExtension"); + LOAD(glx.xrender_handle, glx.XRenderFindVisualFormat, "XRenderFindVisualFormat"); + } + glx.handle = open_first(gl_sonames); + if (!glx.handle) { + host->set_error("GLX: Failed to load GLX"); + return false; + } + LOAD(glx.handle, glx.GetFBConfigs, "glXGetFBConfigs"); + LOAD(glx.handle, glx.GetFBConfigAttrib, "glXGetFBConfigAttrib"); + LOAD(glx.handle, glx.ChooseFBConfig, "glXChooseFBConfig"); + LOAD(glx.handle, glx.GetClientString, "glXGetClientString"); + LOAD(glx.handle, glx.QueryExtension, "glXQueryExtension"); + LOAD(glx.handle, glx.QueryVersion, "glXQueryVersion"); + LOAD(glx.handle, glx.DestroyContext, "glXDestroyContext"); + LOAD(glx.handle, glx.MakeCurrent, "glXMakeCurrent"); + LOAD(glx.handle, glx.SwapBuffers, "glXSwapBuffers"); + LOAD(glx.handle, glx.QueryExtensionsString, "glXQueryExtensionsString"); + LOAD(glx.handle, glx.CreateNewContext, "glXCreateNewContext"); + LOAD(glx.handle, glx.CreateWindow, "glXCreateWindow"); + LOAD(glx.handle, glx.DestroyWindow, "glXDestroyWindow"); + LOAD(glx.handle, glx.GetProcAddress, "glXGetProcAddress"); + LOAD(glx.handle, glx.GetProcAddressARB, "glXGetProcAddressARB"); + LOAD(glx.handle, glx.GetVisualFromFBConfig, "glXGetVisualFromFBConfig"); + return true; +} +#undef LOAD + +static bool +extension_supported(const char *name) { + const char *extensions = glx.QueryExtensionsString(glx.display, glx.screen); + return extensions && gl_extension_in_string(name, extensions); +} + +static gl_proc +get_proc_address(const char *name) { + if (glx.GetProcAddress) return glx.GetProcAddress((const unsigned char *)name); + if (glx.GetProcAddressARB) return glx.GetProcAddressARB((const unsigned char *)name); + gl_proc ans = NULL; + *(void **)&ans = dlsym(glx.handle, name); + return ans; +} + +#define LOAD_EXT(dest, name) \ + do { \ + gl_proc p_ = get_proc_address(name); \ + memcpy(&(dest), &p_, sizeof(p_)); \ + } while (0) + +static bool +initialize(Display *display, int screen) { + if (glx.initialized) { + if (display != glx.display) { + host->set_error("GLX: All windows must be on the same X11 display"); + return false; + } + return true; + } + if (!load_libraries()) return false; + glx.display = display; + glx.screen = screen < 0 ? glx.XDefaultScreen(display) : screen; + int ev, err; + glx.xrender_available = glx.xrender_handle && glx.XRenderQueryExtension(display, &ev, &err); + if (!glx.QueryExtension(display, &glx.error_base, &glx.event_base)) { + host->set_error("GLX: GLX extension not found"); + return false; + } + if (!glx.QueryVersion(display, &glx.major, &glx.minor)) { + host->set_error("GLX: Failed to query GLX version"); + return false; + } + if (glx.major == 1 && glx.minor < 3) { + host->set_error("GLX: GLX version 1.3 is required"); + return false; + } + if (extension_supported("GLX_EXT_swap_control")) { + LOAD_EXT(glx.SwapIntervalEXT, "glXSwapIntervalEXT"); + glx.EXT_swap_control = glx.SwapIntervalEXT != NULL; + } + if (extension_supported("GLX_SGI_swap_control")) { + LOAD_EXT(glx.SwapIntervalSGI, "glXSwapIntervalSGI"); + glx.SGI_swap_control = glx.SwapIntervalSGI != NULL; + } + if (extension_supported("GLX_MESA_swap_control")) { + LOAD_EXT(glx.SwapIntervalMESA, "glXSwapIntervalMESA"); + glx.MESA_swap_control = glx.SwapIntervalMESA != NULL; + } + glx.ARB_framebuffer_sRGB = extension_supported("GLX_ARB_framebuffer_sRGB"); + glx.EXT_framebuffer_sRGB = extension_supported("GLX_EXT_framebuffer_sRGB"); + if (extension_supported("GLX_ARB_create_context")) { + LOAD_EXT(glx.CreateContextAttribsARB, "glXCreateContextAttribsARB"); + glx.ARB_create_context = glx.CreateContextAttribsARB != NULL; + } + glx.initialized = true; + return true; +} +#undef LOAD_EXT + +static int +fb_config_attrib(GLXFBConfig config, int attrib) { + int value = 0; + glx.GetFBConfigAttrib(glx.display, config, attrib, &value); + return value; +} + +static bool +is_visual_transparent(Visual *visual) { + if (!glx.xrender_available) return false; + XRenderPictFormat *pf = glx.XRenderFindVisualFormat(glx.display, visual); + return pf && pf->direct.alphaMask; +} + +static GLXFBConfig * +query_fb_configs(bool trust_window_bit, int *count, bool use_best_color_depth) { + int attribs[32]; + int pos = 0; +#define ATTR(x, y) \ + { \ + attribs[pos++] = x; \ + attribs[pos++] = y; \ + } + ATTR(GLX_DOUBLEBUFFER, True); + // kitty uses neither depth nor stencil buffers + ATTR(GLX_DEPTH_SIZE, 0); + ATTR(GLX_STENCIL_SIZE, 0); + if (use_best_color_depth) { + // Ask for the highest available R+G+B+A color depth. This hopefully + // works with 10bit (r=10, g=10, b=10, a=2) visuals + ATTR(GLX_RED_SIZE, 1); + ATTR(GLX_GREEN_SIZE, 1); + ATTR(GLX_BLUE_SIZE, 1); + ATTR(GLX_ALPHA_SIZE, 1); + } else { + ATTR(GLX_RED_SIZE, 8); + ATTR(GLX_GREEN_SIZE, 8); + ATTR(GLX_BLUE_SIZE, 8); + ATTR(GLX_ALPHA_SIZE, 8); + } + if (!trust_window_bit) ATTR(GLX_DRAWABLE_TYPE, 0); + ATTR(None, None); +#undef ATTR + return glx.ChooseFBConfig(glx.display, glx.screen, attribs, count); +} + +// Return the GLXFBConfig most closely matching the specified config +static bool +choose_fb_config(const GPUSurfaceConfig *desired, GLXFBConfig *result) { + if (glx.chosen.valid && glx.chosen.transparent == desired->transparent && glx.chosen.srgb == desired->srgb) { + *result = glx.chosen.config; + return true; + } + // HACK: This is a workaround for Chromium (VirtualBox GL) not setting the + // window bit on any GLXFBConfigs + const char *vendor = glx.GetClientString(glx.display, GLX_VENDOR); + const bool trust_window_bit = !(vendor && strcmp(vendor, "Chromium") == 0); + int count = 0; + GLXFBConfig *configs = query_fb_configs(trust_window_bit, &count, false); + if (!configs || !count) { + configs = query_fb_configs(trust_window_bit, &count, true); + if (!configs || !count) { + host->set_error("GLX: No GLXFBConfigs returned"); + return false; + } + } + int ans_idx = 0; + for (int i = 0; i < count; i++) { + const GLXFBConfig n = configs[i]; + bool transparency_matches = true, srgb_matches = true; + if (desired->transparent) { + transparency_matches = false; + XVisualInfo *vi = glx.GetVisualFromFBConfig(glx.display, n); + if (vi) { + if (is_visual_transparent(vi->visual)) transparency_matches = true; + glx.XFree(vi); + } + } + if (desired->srgb && (glx.ARB_framebuffer_sRGB || glx.EXT_framebuffer_sRGB)) { + srgb_matches = fb_config_attrib(n, GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB) ? true : false; + } + if (transparency_matches && srgb_matches) { + ans_idx = i; + break; + } + } + *result = configs[ans_idx]; + glx.chosen.valid = true; + glx.chosen.transparent = desired->transparent; + glx.chosen.srgb = desired->srgb; + glx.chosen.config = configs[ans_idx]; + glx.XFree(configs); + return true; +} + +static bool +choose_native_visual(const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint64_t *visual_id) { + *visual_id = 0; + if (native->platform != GPU_PLATFORM_X11 || !native->display) { + host->set_error("GLX: Only X11 displays are supported"); + return false; + } + if (!initialize(native->display, native->screen)) return false; + GLXFBConfig fbconfig; + if (!choose_fb_config(config, &fbconfig)) return false; + XVisualInfo *vi = glx.GetVisualFromFBConfig(glx.display, fbconfig); + if (!vi) { + host->set_error("GLX: Failed to retrieve Visual for GLXFBConfig"); + return false; + } + *visual_id = vi->visualid; + glx.XFree(vi); + return true; +} + +static bool +make_current(GLSurface *s) { + if (!glx.initialized) return true; + if (s) { + if (!glx.MakeCurrent(glx.display, s->window, s->context)) { + host->set_error("GLX: Failed to make context current"); + return false; + } + } else { + if (!glx.MakeCurrent(glx.display, None, NULL)) { + host->set_error("GLX: Failed to clear current context"); + return false; + } + } + return true; +} + +static void +surface_destroy(GLSurface *s) { + if (!s) return; + if (s->window) glx.DestroyWindow(glx.display, s->window); + if (s->context) glx.DestroyContext(glx.display, s->context); + for (GLSurface **p = &all_surfaces; *p; p = &(*p)->next) { + if (*p == s) { + *p = s->next; + break; + } + } + free(s); +} + +static GLSurface * +surface_create(const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint32_t width, uint32_t height) { + (void)width; + (void)height; + if (native->platform != GPU_PLATFORM_X11 || !native->display || !native->x11_window) { + host->set_error("GLX: Only X11 windows are supported"); + return NULL; + } + if (!initialize(native->display, native->screen)) return NULL; + GLXFBConfig fbconfig; + if (!choose_fb_config(config, &fbconfig)) return NULL; + GLSurface *s = calloc(1, sizeof(GLSurface)); + if (!s) { + host->set_error("GLX: Out of memory"); + return NULL; + } + s->next = all_surfaces; + all_surfaces = s; + // Share objects with any existing context + GLXContext share = s->next ? s->next->context : NULL; + // X errors are captured by the windowing system's error handler + host->x11_push_error_trap(); + if (glx.ARB_create_context) { + const int attribs[] = { + GLX_CONTEXT_MAJOR_VERSION_ARB, + OPENGL_REQUIRED_VERSION_MAJOR, + GLX_CONTEXT_MINOR_VERSION_ARB, + OPENGL_REQUIRED_VERSION_MINOR, + GLX_CONTEXT_FLAGS_ARB, + GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, + None, + None, + }; + s->context = glx.CreateContextAttribsARB(glx.display, fbconfig, share, True, attribs); + } else { + s->context = glx.CreateNewContext(glx.display, fbconfig, GLX_RGBA_TYPE, share, True); + } + // Waits for the server to process the requests, if needed + const int x11_error_code = host->x11_pop_error_trap(); + if (!s->context) { + char buf[512]; + glx.XGetErrorText(glx.display, x11_error_code, buf, sizeof(buf)); + host->set_error( + "GLX: Failed to create context: %s. kitty requires working OpenGL %d.%d drivers.", + buf, + OPENGL_REQUIRED_VERSION_MAJOR, + OPENGL_REQUIRED_VERSION_MINOR); + surface_destroy(s); + return NULL; + } + s->window = glx.CreateWindow(glx.display, fbconfig, (Window)native->x11_window, NULL); + if (!s->window) { + host->set_error("GLX: Failed to create window"); + surface_destroy(s); + return NULL; + } + return s; +} + +static void +surface_resize(GLSurface *s, uint32_t width, uint32_t height) { + // GLX drawables are resized along with their X11 window + (void)s; + (void)width; + (void)height; +} + +static bool +present(GLSurface *s) { + glx.SwapBuffers(glx.display, s->window); + return true; +} + +static void +set_swap_interval(GLSurface *s, int interval) { + if (glx.EXT_swap_control) glx.SwapIntervalEXT(glx.display, s->window, interval); + else if (glx.MESA_swap_control) glx.SwapIntervalMESA(interval); + else if (glx.SGI_swap_control) { + if (interval > 0) glx.SwapIntervalSGI(interval); + } +} + +static void +native_changed(GLSurface *s) { + (void)s; +} + +static bool +recreate(GLSurface *s) { + (void)s; + host->set_error("GLX: Recreating surfaces is not supported"); + return false; +} + +static void +terminate(void) { + while (all_surfaces) surface_destroy(all_surfaces); + // libGL is never unloaded as doing so while the X11 display is still open + // makes XCloseDisplay crash + glx.initialized = false; + glx.chosen.valid = false; + glx.display = NULL; +} + +const GLPlatform * +glx_platform(const GLPlatformHost *h) { + static const GLPlatform ans = { + .name = "GLX", + .choose_native_visual = choose_native_visual, + .surface_create = surface_create, + .surface_destroy = surface_destroy, + .make_current = make_current, + .surface_resize = surface_resize, + .present = present, + .set_swap_interval = set_swap_interval, + .native_changed = native_changed, + .recreate = recreate, + .get_proc_address = get_proc_address, + .terminate = terminate, + }; + host = h; + return &ans; +} diff --git a/gpu/opengl/nsgl.m b/gpu/opengl/nsgl.m new file mode 100644 index 000000000..5338d6616 --- /dev/null +++ b/gpu/opengl/nsgl.m @@ -0,0 +1,251 @@ +/* + * nsgl.m + * Copyright (C) 2026 Kovid Goyal + * Based on nsgl_context.m from GLFW, Copyright (c) 2009-2019 Camilla Löwy + * + * Distributed under terms of the GPL3 license. + */ + +// OpenGL contexts for Cocoa windows, created using NSOpenGLContext + +#include "platform.h" +#include "version.h" +#import +#include +#include + +struct GLSurface { + NSOpenGLPixelFormat *pixel_format; + NSOpenGLContext *context; + NSView *view; + bool high_resolution; +}; + +static const GLPlatformHost *host = NULL; +static CFBundleRef framework = NULL; +// We use a globally shared context across all OS Windows so that if all OS +// Windows are closed the context does not have to be recreated with all +// associated data lost. On Apple kitty can remain running with no OS Windows. +static NSOpenGLContext *globally_shared_context = nil; + +static bool +choose_native_visual(const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint64_t *visual_id) { + (void)native; + (void)config; + *visual_id = 0; + return true; +} + +static bool +make_current(GLSurface *s) { + if (s) [s->context makeCurrentContext]; + else [NSOpenGLContext clearCurrentContext]; + return true; +} + +static void +surface_destroy(GLSurface *s) { + if (!s) return; + @autoreleasepool { + if (s->context != nil) { + if ([NSOpenGLContext currentContext] == s->context) [NSOpenGLContext clearCurrentContext]; + [s->context release]; + } + [s->pixel_format release]; + [s->view release]; + } + free(s); +} + +static void +attach_to_view(GLSurface *s, NSOpenGLContext *context) { + [s->view setWantsBestResolutionOpenGLSurface:(s->high_resolution ? YES : NO)]; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + [context setView:s->view]; +#pragma clang diagnostic pop +} + +static GLSurface * +surface_create(const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint32_t width, uint32_t height) { + (void)width; + (void)height; + if (native->platform != GPU_PLATFORM_COCOA || !native->handle) { + host->set_error("NSGL: Only Cocoa windows are supported"); + return NULL; + } + if (!framework) { + framework = CFBundleGetBundleWithIdentifier(CFSTR("com.apple.opengl")); + if (framework == NULL) { + host->set_error("NSGL: Failed to locate OpenGL framework"); + return NULL; + } + } + GLSurface *s = calloc(1, sizeof(GLSurface)); + if (!s) { + host->set_error("NSGL: Out of memory"); + return NULL; + } + s->view = [(NSView *)native->handle retain]; + s->high_resolution = config->high_resolution; + + NSOpenGLPixelFormatAttribute attribs[40]; + int index = 0; +#define add_attrib(a) attribs[index++] = a +#define set_attrib(a, v) \ + { \ + add_attrib(a); \ + add_attrib(v); \ + } + add_attrib(NSOpenGLPFAAccelerated); + add_attrib(NSOpenGLPFAClosestPolicy); + if (config->allow_offline_renderers) { + add_attrib(NSOpenGLPFAAllowOfflineRenderers); + // NOTE: This replaces the NSSupportsAutomaticGraphicsSwitching key in + // Info.plist for unbundled applications + // HACK: This assumes that NSOpenGLPixelFormat will remain + // a straightforward wrapper of its CGL counterpart + add_attrib(kCGLPFASupportsAutomaticGraphicsSwitching); + } +#if OPENGL_REQUIRED_VERSION_MAJOR >= 4 + set_attrib(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion4_1Core); +#else + set_attrib(NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core); +#endif + set_attrib(NSOpenGLPFAColorSize, 24); + set_attrib(NSOpenGLPFAAlphaSize, 8); + // kitty uses neither depth nor stencil buffers + set_attrib(NSOpenGLPFADepthSize, 0); + set_attrib(NSOpenGLPFAStencilSize, 0); + add_attrib(NSOpenGLPFADoubleBuffer); + set_attrib(NSOpenGLPFASampleBuffers, 0); + // NOTE: All NSOpenGLPixelFormats on the relevant cards support sRGB + // framebuffer, so there's no need (and no way) to request it + add_attrib(0); +#undef add_attrib +#undef set_attrib + + s->pixel_format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attribs]; + if (s->pixel_format == nil) { + host->set_error("NSGL: Failed to find a suitable pixel format"); + surface_destroy(s); + return NULL; + } + s->context = [[NSOpenGLContext alloc] initWithFormat:s->pixel_format shareContext:globally_shared_context]; + if (s->context == nil) { + host->set_error( + "NSGL: Failed to create OpenGL context. kitty requires working OpenGL %d.%d drivers.", + OPENGL_REQUIRED_VERSION_MAJOR, + OPENGL_REQUIRED_VERSION_MINOR); + surface_destroy(s); + return NULL; + } + if (globally_shared_context == nil) globally_shared_context = [s->context retain]; + if (config->transparent) { + GLint opaque = 0; + [s->context setValues:&opaque forParameter:NSOpenGLContextParameterSurfaceOpacity]; + } + // Swap intervals do not work as of Mojave, kitty uses CVDisplayLink instead + GLint interval = 0; + [s->context setValues:&interval forParameter:NSOpenGLContextParameterSwapInterval]; + attach_to_view(s, s->context); + return s; +} + +static void +surface_resize(GLSurface *s, uint32_t width, uint32_t height) { + (void)width; + (void)height; + // The drawable is updated by native_changed() + (void)s; +} + +static bool +present(GLSurface *s) { + [s->context flushBuffer]; + return true; +} + +static void +set_swap_interval(GLSurface *s, int interval) { + // As of Mojave this does not work so kitty uses CVDisplayLink instead + (void)s; + (void)interval; +} + +static void +native_changed(GLSurface *s) { + @try { + [s->context update]; + } @catch (NSException *e) { host->log_error("Failed to update NSGL Context object with error: %s (%s)", [[e name] UTF8String], [[e reason] UTF8String]); } +} + +static bool +recreate(GLSurface *s) { + @try { + NSOpenGLContext *old_context = s->context; + // Create a new context sharing resources with the old one + NSOpenGLContext *new_context = [[NSOpenGLContext alloc] initWithFormat:s->pixel_format shareContext:old_context]; + if (new_context == nil) { + host->set_error("NSGL: Failed to create OpenGL context"); + return false; + } + // Copy settings from old context + GLint opacity = 0; + [old_context getValues:&opacity forParameter:NSOpenGLContextParameterSurfaceOpacity]; + [new_context setValues:&opacity forParameter:NSOpenGLContextParameterSurfaceOpacity]; + GLint interval = 0; + [new_context setValues:&interval forParameter:NSOpenGLContextParameterSwapInterval]; + // Detach old context + [NSOpenGLContext clearCurrentContext]; + [old_context clearDrawable]; + // Attach new context to the view + attach_to_view(s, new_context); + [new_context makeCurrentContext]; + [new_context update]; + // Replace context + s->context = new_context; + [old_context release]; + } @catch (NSException *e) { + host->set_error("Failed to recreate NSGL context: %s (%s)", [[e name] UTF8String], [[e reason] UTF8String]); + return false; + } + return true; +} + +static gl_proc +get_proc_address(const char *name) { + CFStringRef symbol_name = CFStringCreateWithCString(kCFAllocatorDefault, name, kCFStringEncodingASCII); + gl_proc symbol = NULL; + *(void **)&symbol = CFBundleGetFunctionPointerForName(framework, symbol_name); + CFRelease(symbol_name); + return symbol; +} + +static void +terminate(void) { + if (globally_shared_context != nil) { + [globally_shared_context release]; + globally_shared_context = nil; + } +} + +const GLPlatform * +nsgl_platform(const GLPlatformHost *h) { + static const GLPlatform ans = { + .name = "NSGL", + .choose_native_visual = choose_native_visual, + .surface_create = surface_create, + .surface_destroy = surface_destroy, + .make_current = make_current, + .surface_resize = surface_resize, + .present = present, + .set_swap_interval = set_swap_interval, + .native_changed = native_changed, + .recreate = recreate, + .get_proc_address = get_proc_address, + .terminate = terminate, + }; + host = h; + return &ans; +} diff --git a/gpu/opengl/platform.h b/gpu/opengl/platform.h new file mode 100644 index 000000000..0747cc360 --- /dev/null +++ b/gpu/opengl/platform.h @@ -0,0 +1,63 @@ +/* + * platform.h + * Copyright (C) 2026 Kovid Goyal + * + * Distributed under terms of the GPL3 license. + */ + +// The interface between the OpenGL driver and the code that creates OpenGL +// contexts for native windows using a platform specific API: GLX on X11, EGL +// on Wayland and NSGL on macOS. + +#pragma once + +#include "../api.h" +#include + +typedef void (*gl_proc)(void); + +// Callbacks into the driver for error reporting +typedef struct GLPlatformHost { + // Record an error, retrievable with last_error() + void (*set_error)(const char *fmt, ...) __attribute__((format(printf, 1, 2))); + // Report a non-fatal problem to the user + void (*log_error)(const char *fmt, ...) __attribute__((format(printf, 1, 2))); + // Print debug output, only if debug rendering is enabled + void (*debug)(const char *fmt, ...) __attribute__((format(printf, 1, 2))); + // X11: Capture X errors, see x11_push_error_trap() in GPUDriverInitParams + void (*x11_push_error_trap)(void); + int (*x11_pop_error_trap)(void); +} GLPlatformHost; + +// A platform specific OpenGL context together with the drawable it renders to. +// Every context created by a platform shares objects with all other contexts +// created by that platform. +typedef struct GLSurface GLSurface; + +typedef struct GLPlatform { + const char *name; + bool (*choose_native_visual)(const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint64_t *visual_id); + GLSurface *(*surface_create)(const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint32_t width, uint32_t height); + void (*surface_destroy)(GLSurface *s); + // NULL to make no context current + bool (*make_current)(GLSurface *s); + void (*surface_resize)(GLSurface *s, uint32_t width, uint32_t height); + bool (*present)(GLSurface *s); + void (*set_swap_interval)(GLSurface *s, int interval); + void (*native_changed)(GLSurface *s); + bool (*recreate)(GLSurface *s); + // Must be called with a current context + gl_proc (*get_proc_address)(const char *name); + // Release all resources, all surfaces must have been destroyed + void (*terminate)(void); +} GLPlatform; + +#ifdef __APPLE__ +const GLPlatform *nsgl_platform(const GLPlatformHost *host); +#else +const GLPlatform *glx_platform(const GLPlatformHost *host); +const GLPlatform *egl_platform(const GLPlatformHost *host); +#endif + +// Returns true if the space separated list of extension names contains name +bool gl_extension_in_string(const char *name, const char *extensions); diff --git a/kitty/fast_data_types.pyi b/kitty/fast_data_types.pyi index 3c07dd32a..c96385730 100644 --- a/kitty/fast_data_types.pyi +++ b/kitty/fast_data_types.pyi @@ -240,7 +240,6 @@ GLFW_JOYSTICK_15: int GLFW_JOYSTICK_16: int GLFW_JOYSTICK_LAST: int GLFW_NOT_INITIALIZED: int -GLFW_NO_CURRENT_CONTEXT: int GLFW_INVALID_ENUM: int GLFW_INVALID_VALUE: int GLFW_OUT_OF_MEMORY: int @@ -255,38 +254,7 @@ GLFW_VISIBLE: int GLFW_DECORATED: int GLFW_AUTO_ICONIFY: int GLFW_FLOATING: int -GLFW_RED_BITS: int -GLFW_GREEN_BITS: int -GLFW_BLUE_BITS: int -GLFW_ALPHA_BITS: int -GLFW_DEPTH_BITS: int -GLFW_STENCIL_BITS: int -GLFW_ACCUM_RED_BITS: int -GLFW_ACCUM_GREEN_BITS: int -GLFW_ACCUM_BLUE_BITS: int -GLFW_ACCUM_ALPHA_BITS: int -GLFW_AUX_BUFFERS: int -GLFW_STEREO: int -GLFW_SAMPLES: int -GLFW_SRGB_CAPABLE: int GLFW_REFRESH_RATE: int -GLFW_DOUBLEBUFFER: int -GLFW_CLIENT_API: int -GLFW_CONTEXT_VERSION_MAJOR: int -GLFW_CONTEXT_VERSION_MINOR: int -GLFW_CONTEXT_REVISION: int -GLFW_CONTEXT_ROBUSTNESS: int -GLFW_OPENGL_FORWARD_COMPAT: int -GLFW_CONTEXT_DEBUG: int -GLFW_OPENGL_PROFILE: int -GLFW_OPENGL_API: int -GLFW_OPENGL_ES_API: int -GLFW_NO_ROBUSTNESS: int -GLFW_NO_RESET_NOTIFICATION: int -GLFW_LOSE_CONTEXT_ON_RESET: int -GLFW_OPENGL_ANY_PROFILE: int -GLFW_OPENGL_CORE_PROFILE: int -GLFW_OPENGL_COMPAT_PROFILE: int GLFW_CURSOR: int GLFW_STICKY_KEYS: int GLFW_STICKY_MOUSE_BUTTONS: int diff --git a/kitty/glfw-wrapper.c b/kitty/glfw-wrapper.c index 9c0c3daa7..2a650ac41 100644 --- a/kitty/glfw-wrapper.c +++ b/kitty/glfw-wrapper.c @@ -287,6 +287,12 @@ load_glfw(const char* path) { *(void **) (&glfwSetFramebufferSizeCallback_impl) = dlsym(handle, "glfwSetFramebufferSizeCallback"); if (glfwSetFramebufferSizeCallback_impl == NULL) fail("Failed to load glfw function glfwSetFramebufferSizeCallback with error: %s", dlerror()); + *(void **) (&glfwSetNativeSurfaceChangedCallback_impl) = dlsym(handle, "glfwSetNativeSurfaceChangedCallback"); + if (glfwSetNativeSurfaceChangedCallback_impl == NULL) fail("Failed to load glfw function glfwSetNativeSurfaceChangedCallback with error: %s", dlerror()); + + *(void **) (&glfwWindowContentsPresented_impl) = dlsym(handle, "glfwWindowContentsPresented"); + if (glfwWindowContentsPresented_impl == NULL) fail("Failed to load glfw function glfwWindowContentsPresented with error: %s", dlerror()); + *(void **) (&glfwSetWindowContentScaleCallback_impl) = dlsym(handle, "glfwSetWindowContentScaleCallback"); if (glfwSetWindowContentScaleCallback_impl == NULL) fail("Failed to load glfw function glfwSetWindowContentScaleCallback with error: %s", dlerror()); @@ -437,24 +443,6 @@ load_glfw(const char* path) { *(void **) (&glfwGetTime_impl) = dlsym(handle, "glfwGetTime"); if (glfwGetTime_impl == NULL) fail("Failed to load glfw function glfwGetTime with error: %s", dlerror()); - *(void **) (&glfwMakeContextCurrent_impl) = dlsym(handle, "glfwMakeContextCurrent"); - if (glfwMakeContextCurrent_impl == NULL) fail("Failed to load glfw function glfwMakeContextCurrent with error: %s", dlerror()); - - *(void **) (&glfwGetCurrentContext_impl) = dlsym(handle, "glfwGetCurrentContext"); - if (glfwGetCurrentContext_impl == NULL) fail("Failed to load glfw function glfwGetCurrentContext with error: %s", dlerror()); - - *(void **) (&glfwSwapBuffers_impl) = dlsym(handle, "glfwSwapBuffers"); - if (glfwSwapBuffers_impl == NULL) fail("Failed to load glfw function glfwSwapBuffers with error: %s", dlerror()); - - *(void **) (&glfwSwapInterval_impl) = dlsym(handle, "glfwSwapInterval"); - if (glfwSwapInterval_impl == NULL) fail("Failed to load glfw function glfwSwapInterval with error: %s", dlerror()); - - *(void **) (&glfwExtensionSupported_impl) = dlsym(handle, "glfwExtensionSupported"); - if (glfwExtensionSupported_impl == NULL) fail("Failed to load glfw function glfwExtensionSupported with error: %s", dlerror()); - - *(void **) (&glfwGetProcAddress_impl) = dlsym(handle, "glfwGetProcAddress"); - if (glfwGetProcAddress_impl == NULL) fail("Failed to load glfw function glfwGetProcAddress with error: %s", dlerror()); - *(void **) (&glfwVulkanSupported_impl) = dlsym(handle, "glfwVulkanSupported"); if (glfwVulkanSupported_impl == NULL) fail("Failed to load glfw function glfwVulkanSupported with error: %s", dlerror()); @@ -464,8 +452,8 @@ load_glfw(const char* path) { *(void **) (&glfwGetCocoaWindow_impl) = dlsym(handle, "glfwGetCocoaWindow"); if (glfwGetCocoaWindow_impl == NULL) dlerror(); // clear error indicator - *(void **) (&glfwGetNSGLContext_impl) = dlsym(handle, "glfwGetNSGLContext"); - if (glfwGetNSGLContext_impl == NULL) dlerror(); // clear error indicator + *(void **) (&glfwGetCocoaView_impl) = dlsym(handle, "glfwGetCocoaView"); + if (glfwGetCocoaView_impl == NULL) dlerror(); // clear error indicator *(void **) (&glfwGetCocoaMonitor_impl) = dlsym(handle, "glfwGetCocoaMonitor"); if (glfwGetCocoaMonitor_impl == NULL) dlerror(); // clear error indicator @@ -491,9 +479,6 @@ load_glfw(const char* path) { *(void **) (&glfwCocoaRequestRenderFrame_impl) = dlsym(handle, "glfwCocoaRequestRenderFrame"); if (glfwCocoaRequestRenderFrame_impl == NULL) dlerror(); // clear error indicator - *(void **) (&glfwCocoaRecreateGLDrawable_impl) = dlsym(handle, "glfwCocoaRecreateGLDrawable"); - if (glfwCocoaRecreateGLDrawable_impl == NULL) dlerror(); // clear error indicator - *(void **) (&glfwCocoaSetWindowResizeCallback_impl) = dlsym(handle, "glfwCocoaSetWindowResizeCallback"); if (glfwCocoaSetWindowResizeCallback_impl == NULL) dlerror(); // clear error indicator @@ -503,6 +488,18 @@ load_glfw(const char* path) { *(void **) (&glfwGetX11Window_impl) = dlsym(handle, "glfwGetX11Window"); if (glfwGetX11Window_impl == NULL) dlerror(); // clear error indicator + *(void **) (&glfwX11PushErrorTrap_impl) = dlsym(handle, "glfwX11PushErrorTrap"); + if (glfwX11PushErrorTrap_impl == NULL) dlerror(); // clear error indicator + + *(void **) (&glfwX11PopErrorTrap_impl) = dlsym(handle, "glfwX11PopErrorTrap"); + if (glfwX11PopErrorTrap_impl == NULL) dlerror(); // clear error indicator + + *(void **) (&glfwGetWaylandDisplay_impl) = dlsym(handle, "glfwGetWaylandDisplay"); + if (glfwGetWaylandDisplay_impl == NULL) dlerror(); // clear error indicator + + *(void **) (&glfwGetWaylandWindow_impl) = dlsym(handle, "glfwGetWaylandWindow"); + if (glfwGetWaylandWindow_impl == NULL) dlerror(); // clear error indicator + *(void **) (&glfwSetPrimarySelectionString_impl) = dlsym(handle, "glfwSetPrimarySelectionString"); if (glfwSetPrimarySelectionString_impl == NULL) dlerror(); // clear error indicator diff --git a/kitty/glfw-wrapper.h b/kitty/glfw-wrapper.h index 6ba40dc08..a0304f4e5 100644 --- a/kitty/glfw-wrapper.h +++ b/kitty/glfw-wrapper.h @@ -453,16 +453,6 @@ typedef struct GLFWTouchEvent { * function that requires initialization. */ #define GLFW_NOT_INITIALIZED 0x00010001 -/*! @brief No context is current for this thread. - * - * This occurs if a GLFW function was called that needs and operates on the - * current OpenGL or OpenGL ES context but no context is current on the calling - * thread. One such function is @ref glfwSwapInterval. - * - * @analysis Application programmer error. Ensure a context is current before - * calling functions that require a current context. - */ -#define GLFW_NO_CURRENT_CONTEXT 0x00010002 /*! @brief One of the arguments to the function was an invalid enum value. * * One of the arguments to the function was an invalid enum value, for example @@ -553,14 +543,6 @@ typedef struct GLFWTouchEvent { * the user, as appropriate. */ #define GLFW_FORMAT_UNAVAILABLE 0x00010009 -/*! @brief The specified window does not have an OpenGL or OpenGL ES context. - * - * A window that does not have an OpenGL or OpenGL ES context was passed to - * a function that requires it to have one. - * - * @analysis Application programmer error. Fix the offending call. - */ -#define GLFW_NO_WINDOW_CONTEXT 0x0001000A /*! @brief The requested feature is not provided by the platform. * * The requested feature is not provided by the platform, so GLFW is unable to @@ -675,158 +657,12 @@ typedef struct GLFWTouchEvent { * Occlusion [window attribute](@ref GLFW_OCCLUDED_attrib). */ #define GLFW_OCCLUDED 0x0002000E -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_RED_BITS). - */ -#define GLFW_RED_BITS 0x00021001 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_GREEN_BITS). - */ -#define GLFW_GREEN_BITS 0x00021002 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_BLUE_BITS). - */ -#define GLFW_BLUE_BITS 0x00021003 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_ALPHA_BITS). - */ -#define GLFW_ALPHA_BITS 0x00021004 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_DEPTH_BITS). - */ -#define GLFW_DEPTH_BITS 0x00021005 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_STENCIL_BITS). - */ -#define GLFW_STENCIL_BITS 0x00021006 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_ACCUM_RED_BITS). - */ -#define GLFW_ACCUM_RED_BITS 0x00021007 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_ACCUM_GREEN_BITS). - */ -#define GLFW_ACCUM_GREEN_BITS 0x00021008 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_ACCUM_BLUE_BITS). - */ -#define GLFW_ACCUM_BLUE_BITS 0x00021009 -/*! @brief Framebuffer bit depth hint. - * - * Framebuffer bit depth [hint](@ref GLFW_ACCUM_ALPHA_BITS). - */ -#define GLFW_ACCUM_ALPHA_BITS 0x0002100A -/*! @brief Framebuffer auxiliary buffer hint. - * - * Framebuffer auxiliary buffer [hint](@ref GLFW_AUX_BUFFERS). - */ -#define GLFW_AUX_BUFFERS 0x0002100B -/*! @brief OpenGL stereoscopic rendering hint. - * - * OpenGL stereoscopic rendering [hint](@ref GLFW_STEREO). - */ -#define GLFW_STEREO 0x0002100C -/*! @brief Framebuffer MSAA samples hint. - * - * Framebuffer MSAA samples [hint](@ref GLFW_SAMPLES). - */ -#define GLFW_SAMPLES 0x0002100D -/*! @brief Framebuffer sRGB hint. - * - * Framebuffer sRGB [hint](@ref GLFW_SRGB_CAPABLE). - */ -#define GLFW_SRGB_CAPABLE 0x0002100E /*! @brief Monitor refresh rate hint. * * Monitor refresh rate [hint](@ref GLFW_REFRESH_RATE). */ #define GLFW_REFRESH_RATE 0x0002100F -/*! @brief Framebuffer double buffering hint. - * - * Framebuffer double buffering [hint](@ref GLFW_DOUBLEBUFFER). - */ -#define GLFW_DOUBLEBUFFER 0x00021010 -/*! @brief Context client API hint and attribute. - * - * Context client API [hint](@ref GLFW_CLIENT_API_hint) and - * [attribute](@ref GLFW_CLIENT_API_attrib). - */ -#define GLFW_CLIENT_API 0x00022001 -/*! @brief Context client API major version hint and attribute. - * - * Context client API major version [hint](@ref GLFW_CONTEXT_VERSION_MAJOR_hint) - * and [attribute](@ref GLFW_CONTEXT_VERSION_MAJOR_attrib). - */ -#define GLFW_CONTEXT_VERSION_MAJOR 0x00022002 -/*! @brief Context client API minor version hint and attribute. - * - * Context client API minor version [hint](@ref GLFW_CONTEXT_VERSION_MINOR_hint) - * and [attribute](@ref GLFW_CONTEXT_VERSION_MINOR_attrib). - */ -#define GLFW_CONTEXT_VERSION_MINOR 0x00022003 -/*! @brief Context client API revision number hint and attribute. - * - * Context client API revision number - * [attribute](@ref GLFW_CONTEXT_REVISION_attrib). - */ -#define GLFW_CONTEXT_REVISION 0x00022004 -/*! @brief Context robustness hint and attribute. - * - * Context client API revision number [hint](@ref GLFW_CONTEXT_ROBUSTNESS_hint) - * and [attribute](@ref GLFW_CONTEXT_ROBUSTNESS_attrib). - */ -#define GLFW_CONTEXT_ROBUSTNESS 0x00022005 -/*! @brief OpenGL forward-compatibility hint and attribute. - * - * OpenGL forward-compatibility [hint](@ref GLFW_OPENGL_FORWARD_COMPAT_hint) - * and [attribute](@ref GLFW_OPENGL_FORWARD_COMPAT_attrib). - */ -#define GLFW_OPENGL_FORWARD_COMPAT 0x00022006 -/*! @brief Debug mode context hint and attribute. - * - * Debug mode context [hint](@ref GLFW_CONTEXT_DEBUG_hint) and - * [attribute](@ref GLFW_CONTEXT_DEBUG_attrib). - */ -#define GLFW_CONTEXT_DEBUG 0x00022007 -/*! @brief Legacy name for compatibility. - * - * This is an alias for compatibility with earlier versions. - */ -#define GLFW_OPENGL_DEBUG_CONTEXT GLFW_CONTEXT_DEBUG -/*! @brief OpenGL profile hint and attribute. - * - * OpenGL profile [hint](@ref GLFW_OPENGL_PROFILE_hint) and - * [attribute](@ref GLFW_OPENGL_PROFILE_attrib). - */ -#define GLFW_OPENGL_PROFILE 0x00022008 -/*! @brief Context flush-on-release hint and attribute. - * - * Context flush-on-release [hint](@ref GLFW_CONTEXT_RELEASE_BEHAVIOR_hint) and - * [attribute](@ref GLFW_CONTEXT_RELEASE_BEHAVIOR_attrib). - */ -#define GLFW_CONTEXT_RELEASE_BEHAVIOR 0x00022009 -/*! @brief Context error suppression hint and attribute. - * - * Context error suppression [hint](@ref GLFW_CONTEXT_NO_ERROR_hint) and - * [attribute](@ref GLFW_CONTEXT_NO_ERROR_attrib). - */ -#define GLFW_CONTEXT_NO_ERROR 0x0002200A -/*! @brief Context creation API hint and attribute. - * - * Context creation API [hint](@ref GLFW_CONTEXT_CREATION_API_hint) and - * [attribute](@ref GLFW_CONTEXT_CREATION_API_attrib). - */ -#define GLFW_CONTEXT_CREATION_API 0x0002200B /*! @brief Window content area scaling window * [window hint](@ref GLFW_SCALE_TO_MONITOR). */ @@ -839,10 +675,6 @@ typedef struct GLFWTouchEvent { * [window hint](@ref GLFW_COCOA_FRAME_NAME_hint). */ #define GLFW_COCOA_FRAME_NAME 0x00023002 -/*! @brief macOS specific - * [window hint](@ref GLFW_COCOA_GRAPHICS_SWITCHING_hint). - */ -#define GLFW_COCOA_GRAPHICS_SWITCHING 0x00023003 /*! @brief macOS specific * [window hint](@ref GLFW_COCOA_COLOR_SPACE_hint). */ @@ -865,23 +697,17 @@ typedef enum { * [window hint](@ref GLFW_X11_CLASS_NAME_hint). */ #define GLFW_X11_INSTANCE_NAME 0x00024002 +/*! @brief X11 specific + * The id of the X11 visual to use for the window, as chosen by the GPU driver, + * zero for the default visual. + */ +#define GLFW_X11_VISUAL_ID 0x00024003 #define GLFW_WAYLAND_APP_ID 0x00025001 #define GLFW_WAYLAND_BGCOLOR 0x00025002 #define GLFW_WAYLAND_WINDOW_TAG 0x00025003 /*! @} */ -#define GLFW_NO_API 0 -#define GLFW_OPENGL_API 0x00030001 -#define GLFW_OPENGL_ES_API 0x00030002 - -#define GLFW_NO_ROBUSTNESS 0 -#define GLFW_NO_RESET_NOTIFICATION 0x00031001 -#define GLFW_LOSE_CONTEXT_ON_RESET 0x00031002 - -#define GLFW_OPENGL_ANY_PROFILE 0 -#define GLFW_OPENGL_CORE_PROFILE 0x00032001 -#define GLFW_OPENGL_COMPAT_PROFILE 0x00032002 #define GLFW_CURSOR 0x00033001 #define GLFW_STICKY_KEYS 0x00033002 @@ -893,21 +719,6 @@ typedef enum { #define GLFW_CURSOR_HIDDEN 0x00034002 #define GLFW_CURSOR_DISABLED 0x00034003 -#define GLFW_ANY_RELEASE_BEHAVIOR 0 -#define GLFW_RELEASE_BEHAVIOR_FLUSH 0x00035001 -#define GLFW_RELEASE_BEHAVIOR_NONE 0x00035002 - -#define GLFW_NATIVE_CONTEXT_API 0x00036001 -#define GLFW_EGL_CONTEXT_API 0x00036002 -#define GLFW_OSMESA_CONTEXT_API 0x00036003 - -#define GLFW_ANGLE_PLATFORM_TYPE_NONE 0x00037001 -#define GLFW_ANGLE_PLATFORM_TYPE_OPENGL 0x00037002 -#define GLFW_ANGLE_PLATFORM_TYPE_OPENGLES 0x00037003 -#define GLFW_ANGLE_PLATFORM_TYPE_D3D9 0x00037004 -#define GLFW_ANGLE_PLATFORM_TYPE_D3D11 0x00037005 -#define GLFW_ANGLE_PLATFORM_TYPE_VULKAN 0x00037007 -#define GLFW_ANGLE_PLATFORM_TYPE_METAL 0x00037008 /*! @defgroup shapes Standard cursor shapes * @brief Standard system cursor shapes. @@ -964,11 +775,6 @@ typedef enum { * Joystick hat buttons [init hint](@ref GLFW_JOYSTICK_HAT_BUTTONS). */ #define GLFW_JOYSTICK_HAT_BUTTONS 0x00050001 -/*! @brief ANGLE rendering backend init hint. - * - * ANGLE rendering backend [init hint](@ref GLFW_ANGLE_PLATFORM_TYPE_hint). - */ -#define GLFW_ANGLE_PLATFORM_TYPE 0x00050002 #define GLFW_DEBUG_KEYBOARD 0x00050003 #define GLFW_DEBUG_RENDERING 0x00050004 /*! @brief macOS specific init hint. @@ -991,20 +797,6 @@ typedef enum { * GLFW API types *************************************************************************/ -/*! @brief Client API function pointer type. - * - * Generic function pointer used for returning client API function pointers - * without forcing a cast from a regular pointer. - * - * @sa @ref context_glext - * @sa @ref glfwGetProcAddress - * - * @since Added in version 3.0. - * - * @ingroup context - */ -typedef void (*GLFWglproc)(void); - /*! @brief Vulkan API function pointer type. * * Generic function pointer used for returning Vulkan API function pointers @@ -1468,6 +1260,14 @@ typedef void (*GLFWwindowmaximizefun)(GLFWwindow *, int); */ typedef void (*GLFWframebuffersizefun)(GLFWwindow *, int, int); +/*! @brief The function pointer type for native surface change callbacks. + * + * Called when the native surface a window renders into changes in a way that + * requires the GPU driver to update its drawable, such as on macOS when the + * view is resized or moved to a different screen. + */ +typedef void (*GLFWnativesurfacechangedfun)(GLFWwindow *); + /*! @brief The function pointer type for window content scale callbacks. * * This is the function pointer type for window content scale callbacks. @@ -2100,7 +1900,7 @@ typedef void (*glfwWindowHintString_func)(int, const char*); GFW_EXTERN glfwWindowHintString_func glfwWindowHintString_impl; #define glfwWindowHintString glfwWindowHintString_impl -typedef GLFWwindow* (*glfwCreateWindow_func)(int, int, const char*, GLFWmonitor*, GLFWwindow*, const GLFWLayerShellConfig*); +typedef GLFWwindow* (*glfwCreateWindow_func)(int, int, const char*, GLFWmonitor*, const GLFWLayerShellConfig*); GFW_EXTERN glfwCreateWindow_func glfwCreateWindow_impl; #define glfwCreateWindow glfwCreateWindow_impl @@ -2312,6 +2112,14 @@ typedef GLFWframebuffersizefun (*glfwSetFramebufferSizeCallback_func)(GLFWwindow GFW_EXTERN glfwSetFramebufferSizeCallback_func glfwSetFramebufferSizeCallback_impl; #define glfwSetFramebufferSizeCallback glfwSetFramebufferSizeCallback_impl +typedef GLFWnativesurfacechangedfun (*glfwSetNativeSurfaceChangedCallback_func)(GLFWwindow*, GLFWnativesurfacechangedfun); +GFW_EXTERN glfwSetNativeSurfaceChangedCallback_func glfwSetNativeSurfaceChangedCallback_impl; +#define glfwSetNativeSurfaceChangedCallback glfwSetNativeSurfaceChangedCallback_impl + +typedef void (*glfwWindowContentsPresented_func)(GLFWwindow*); +GFW_EXTERN glfwWindowContentsPresented_func glfwWindowContentsPresented_impl; +#define glfwWindowContentsPresented glfwWindowContentsPresented_impl + typedef GLFWwindowcontentscalefun (*glfwSetWindowContentScaleCallback_func)(GLFWwindow*, GLFWwindowcontentscalefun); GFW_EXTERN glfwSetWindowContentScaleCallback_func glfwSetWindowContentScaleCallback_impl; #define glfwSetWindowContentScaleCallback glfwSetWindowContentScaleCallback_impl @@ -2512,30 +2320,6 @@ typedef monotonic_t (*glfwGetTime_func)(void); GFW_EXTERN glfwGetTime_func glfwGetTime_impl; #define glfwGetTime glfwGetTime_impl -typedef void (*glfwMakeContextCurrent_func)(GLFWwindow*); -GFW_EXTERN glfwMakeContextCurrent_func glfwMakeContextCurrent_impl; -#define glfwMakeContextCurrent glfwMakeContextCurrent_impl - -typedef GLFWwindow* (*glfwGetCurrentContext_func)(void); -GFW_EXTERN glfwGetCurrentContext_func glfwGetCurrentContext_impl; -#define glfwGetCurrentContext glfwGetCurrentContext_impl - -typedef void (*glfwSwapBuffers_func)(GLFWwindow*); -GFW_EXTERN glfwSwapBuffers_func glfwSwapBuffers_impl; -#define glfwSwapBuffers glfwSwapBuffers_impl - -typedef void (*glfwSwapInterval_func)(int); -GFW_EXTERN glfwSwapInterval_func glfwSwapInterval_impl; -#define glfwSwapInterval glfwSwapInterval_impl - -typedef int (*glfwExtensionSupported_func)(const char*); -GFW_EXTERN glfwExtensionSupported_func glfwExtensionSupported_impl; -#define glfwExtensionSupported glfwExtensionSupported_impl - -typedef GLFWglproc (*glfwGetProcAddress_func)(const char*); -GFW_EXTERN glfwGetProcAddress_func glfwGetProcAddress_impl; -#define glfwGetProcAddress glfwGetProcAddress_impl - typedef int (*glfwVulkanSupported_func)(void); GFW_EXTERN glfwVulkanSupported_func glfwVulkanSupported_impl; #define glfwVulkanSupported glfwVulkanSupported_impl @@ -2548,9 +2332,9 @@ typedef void* (*glfwGetCocoaWindow_func)(GLFWwindow*); GFW_EXTERN glfwGetCocoaWindow_func glfwGetCocoaWindow_impl; #define glfwGetCocoaWindow glfwGetCocoaWindow_impl -typedef void* (*glfwGetNSGLContext_func)(GLFWwindow*); -GFW_EXTERN glfwGetNSGLContext_func glfwGetNSGLContext_impl; -#define glfwGetNSGLContext glfwGetNSGLContext_impl +typedef void* (*glfwGetCocoaView_func)(GLFWwindow*); +GFW_EXTERN glfwGetCocoaView_func glfwGetCocoaView_impl; +#define glfwGetCocoaView glfwGetCocoaView_impl typedef uint32_t (*glfwGetCocoaMonitor_func)(GLFWmonitor*); GFW_EXTERN glfwGetCocoaMonitor_func glfwGetCocoaMonitor_impl; @@ -2584,10 +2368,6 @@ typedef void (*glfwCocoaRequestRenderFrame_func)(GLFWwindow*, GLFWcocoarenderfra GFW_EXTERN glfwCocoaRequestRenderFrame_func glfwCocoaRequestRenderFrame_impl; #define glfwCocoaRequestRenderFrame glfwCocoaRequestRenderFrame_impl -typedef bool (*glfwCocoaRecreateGLDrawable_func)(GLFWwindow*); -GFW_EXTERN glfwCocoaRecreateGLDrawable_func glfwCocoaRecreateGLDrawable_impl; -#define glfwCocoaRecreateGLDrawable glfwCocoaRecreateGLDrawable_impl - typedef GLFWcocoarenderframefun (*glfwCocoaSetWindowResizeCallback_func)(GLFWwindow*, GLFWcocoarenderframefun); GFW_EXTERN glfwCocoaSetWindowResizeCallback_func glfwCocoaSetWindowResizeCallback_impl; #define glfwCocoaSetWindowResizeCallback glfwCocoaSetWindowResizeCallback_impl @@ -2600,6 +2380,22 @@ typedef unsigned long (*glfwGetX11Window_func)(GLFWwindow*); GFW_EXTERN glfwGetX11Window_func glfwGetX11Window_impl; #define glfwGetX11Window glfwGetX11Window_impl +typedef void (*glfwX11PushErrorTrap_func)(void); +GFW_EXTERN glfwX11PushErrorTrap_func glfwX11PushErrorTrap_impl; +#define glfwX11PushErrorTrap glfwX11PushErrorTrap_impl + +typedef int (*glfwX11PopErrorTrap_func)(void); +GFW_EXTERN glfwX11PopErrorTrap_func glfwX11PopErrorTrap_impl; +#define glfwX11PopErrorTrap glfwX11PopErrorTrap_impl + +typedef void* (*glfwGetWaylandDisplay_func)(void); +GFW_EXTERN glfwGetWaylandDisplay_func glfwGetWaylandDisplay_impl; +#define glfwGetWaylandDisplay glfwGetWaylandDisplay_impl + +typedef void* (*glfwGetWaylandWindow_func)(GLFWwindow*); +GFW_EXTERN glfwGetWaylandWindow_func glfwGetWaylandWindow_impl; +#define glfwGetWaylandWindow glfwGetWaylandWindow_impl + typedef void (*glfwSetPrimarySelectionString_func)(GLFWwindow*, const char*); GFW_EXTERN glfwSetPrimarySelectionString_func glfwSetPrimarySelectionString_impl; #define glfwSetPrimarySelectionString glfwSetPrimarySelectionString_impl diff --git a/kitty/glfw.c b/kitty/glfw.c index 71e42cefb..f69248664 100644 --- a/kitty/glfw.c +++ b/kitty/glfw.c @@ -29,15 +29,60 @@ typedef struct mouse_cursor { static mouse_cursor cursors[GLFW_INVALID_CURSOR + 1] = {0}; +// Must be called with the surface current static void -apply_swap_interval(int val) { +apply_swap_interval(gpu_surface_t surface, int val) { (void)val; + (void)surface; #ifndef __APPLE__ if (val < 0) val = OPT(sync_to_monitor) && !global_state.is_wayland ? 1 : 0; - glfwSwapInterval(val); + gpu_surface_set_swap_interval(surface, val); #endif } +// GPU surfaces {{{ +static void +native_window_for_gpu(GLFWwindow *w, GPUNativeWindow *ans) { +#ifdef __APPLE__ + *ans = (GPUNativeWindow){.platform = GPU_PLATFORM_COCOA, .handle = w ? glfwGetCocoaView(w) : NULL}; +#else + if (global_state.is_wayland) { + *ans = (GPUNativeWindow){.platform = GPU_PLATFORM_WAYLAND, .display = glfwGetWaylandDisplay(), .handle = w ? glfwGetWaylandWindow(w) : NULL}; + } else { + *ans = (GPUNativeWindow){.platform = GPU_PLATFORM_X11, .display = glfwGetX11Display(), .screen = -1, .x11_window = w ? glfwGetX11Window(w) : 0}; + } +#endif +} + +static GPUSurfaceConfig +gpu_surface_config(bool transparent) { + return (GPUSurfaceConfig){ + .transparent = transparent, + // Request SRGB output buffer + // Prevents kitty from starting on Wayland + NVIDIA, sigh: https://github.com/kovidgoyal/kitty/issues/7021 + // Remove after https://github.com/NVIDIA/egl-wayland/issues/85 is fixed. + // Also apparently mesa has introduced a bug with sRGB surfaces and Wayland. + // Sigh. Wayland is such a pile of steaming crap. + // See https://github.com/kovidgoyal/kitty/issues/7174#issuecomment-2000033873 + // GL_FRAMEBUFFER_SRGB works anyway without this on Wayland. + .srgb = !global_state.is_wayland, + .allow_offline_renderers = true, + .high_resolution = true, + }; +} + +static void +native_surface_changed_callback(GLFWwindow *glfw_window) { + for (size_t i = 0; i < global_state.num_os_windows; i++) { + OSWindow *w = global_state.os_windows + i; + if (w->handle == glfw_window) { + if (w->gpu_surface) gpu_surface_native_changed(w->gpu_surface); + break; + } + } +} +// }}} + void get_platform_dependent_config_values(void *glfw_window) { if (OPT(click_interval) < 0) OPT(click_interval) = glfwGetDoubleClickInterval(glfw_window); @@ -363,7 +408,7 @@ cocoa_out_of_sequence_render(OSWindow *window) { // See https://github.com/kovidgoyal/kitty/issues/9463 if (!current_framebuffer_is_ok()) { debug_rendering("Cocoa OpenGL framebuffer broken, re-creating\n"); - if (!glfwCocoaRecreateGLDrawable(window->handle) || !current_framebuffer_is_ok()) { + if (!gpu_surface_recreate(window->gpu_surface) || !current_framebuffer_is_ok()) { debug_rendering("Cocoa OpenGL framebuffer re-creation failed\n"); request_tick_callback(); return; @@ -405,9 +450,9 @@ change_live_resize_state(OSWindow *w, bool in_progress) { #ifdef __APPLE__ cocoa_out_of_sequence_render(w); #else - GLFWwindow *orig_ctx = make_os_window_context_current(w); - apply_swap_interval(in_progress ? 0 : -1); - if (orig_ctx) glfwMakeContextCurrent(orig_ctx); + gpu_surface_t orig_surface = make_os_window_context_current(w); + apply_swap_interval(w->gpu_surface, in_progress ? 0 : -1); + if (orig_surface) gpu_make_surface_current(orig_surface); #endif } @@ -430,6 +475,9 @@ live_resize_callback(GLFWwindow *w, bool started) { static void framebuffer_size_callback(GLFWwindow *w, int width, int height) { if (!set_callback_window(w)) return; + // The GPU surface must always match the size of the window framebuffer + if (global_state.callback_os_window->gpu_surface && width > 0 && height > 0) + gpu_surface_resize(global_state.callback_os_window->gpu_surface, (uint32_t)width, (uint32_t)height); if (global_state.callback_os_window->ignore_resize_events) return; int min_width, min_height; min_size_for_os_window(global_state.callback_os_window, &min_width, &min_height); @@ -1728,14 +1776,17 @@ set_os_window_icon(PyObject UNUSED *self, PyObject *args) { } -void * +// Makes the GPU surface of the OS Window current, returning the previously +// current surface if it was changed, zero otherwise +gpu_surface_t make_os_window_context_current(OSWindow *w) { - GLFWwindow *current_context = glfwGetCurrentContext(); - if (w->handle != current_context) { - glfwMakeContextCurrent(w->handle); - return current_context; + gpu_surface_t current = gpu_get_current_surface(); + if (w->gpu_surface != current) { + if (!gpu_make_surface_current(w->gpu_surface)) + log_error("Failed to make the GPU surface of OS Window: %llu current with error: %s", w->id, gpu_last_error()); + return current; } - return NULL; + return GPU_NULL_HANDLE; } void @@ -2260,13 +2311,7 @@ set_window_creation_error(bool is_panel) { desc ? " with error: " : "", desc ? desc : ""); } else { - PyErr_Format( - PyExc_OSError, - "Failed to create GLFWwindow%s%s. This usually happens because of old/broken OpenGL drivers. kitty requires working OpenGL %d.%d drivers.", - desc ? " with error: " : "", - desc ? desc : "", - OPENGL_REQUIRED_VERSION_MAJOR, - OPENGL_REQUIRED_VERSION_MINOR); + PyErr_Format(PyExc_OSError, "Failed to create GLFWwindow%s%s", desc ? " with error: " : "", desc ? desc : ""); } } @@ -2360,12 +2405,6 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { #ifndef __APPLE__ glfwConfigureMomentumScroller(OPT(momentum_scroll), -1, -1, 0); #endif - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, OPENGL_REQUIRED_VERSION_MAJOR); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, OPENGL_REQUIRED_VERSION_MINOR); - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true); - // We don't use depth and stencil buffers - glfwWindowHint(GLFW_DEPTH_BITS, 0); - glfwWindowHint(GLFW_STENCIL_BITS, 0); glfwSetApplicationCloseCallback(application_close_requested_callback); glfwSetCurrentSelectionCallback(get_current_selection); glfwSetHasCurrentSelectionCallback(has_current_selection); @@ -2373,17 +2412,8 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { glfwSetIMETextAroundCursorCallback(get_ime_text_around_cursor); glfwSetSystemColorThemeChangeCallback(on_system_color_scheme_change); glfwSetClipboardLostCallback(on_clipboard_lost); - // Request SRGB output buffer - // Prevents kitty from starting on Wayland + NVIDIA, sigh: https://github.com/kovidgoyal/kitty/issues/7021 - // Remove after https://github.com/NVIDIA/egl-wayland/issues/85 is fixed. - // Also apparently mesa has introduced a bug with sRGB surfaces and Wayland. - // Sigh. Wayland is such a pile of steaming crap. - // See https://github.com/kovidgoyal/kitty/issues/7174#issuecomment-2000033873 - // GL_FRAMEBUFFER_SRGB works anyway without this on Wayland. - if (!global_state.is_wayland) glfwWindowHint(GLFW_SRGB_CAPABLE, true); #ifdef __APPLE__ cocoa_set_activation_policy(OPT(macos_hide_from_tasks) || lsc != NULL); - glfwWindowHint(GLFW_COCOA_GRAPHICS_SWITCHING, true); glfwSetApplicationShouldHandleReopen(on_application_reopen); glfwSetApplicationWillFinishLaunching(cocoa_application_lifecycle_event); #endif @@ -2408,6 +2438,20 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { } bool want_semi_transparent = (1.0 - OPT(background_opacity) >= 0.01) || OPT(dynamic_background_opacity); glfwWindowHint(GLFW_TRANSPARENT_FRAMEBUFFER, want_semi_transparent); + const GPUSurfaceConfig surface_config = gpu_surface_config(want_semi_transparent); +#ifndef __APPLE__ + if (!global_state.is_wayland) { + // The GPU driver may need the X11 window to use a particular visual + GPUNativeWindow display; + native_window_for_gpu(NULL, &display); + uint64_t visual_id = 0; + if (!gpu_choose_native_visual(&display, &surface_config, &visual_id)) { + PyErr_Format(PyExc_OSError, "Failed to choose an X11 visual for the window with error: %s", gpu_last_error()); + return NULL; + } + glfwWindowHint(GLFW_X11_VISUAL_ID, (int)visual_id); + } +#endif uint32_t bgcolor = OPT(background); uint32_t bgalpha = (uint32_t)((MAX(0.f, MIN((OPT(background_opacity) * 255), 255.f)))); glfwWindowHint(GLFW_WAYLAND_BGCOLOR, ((bgalpha & 0xff) << 24) | bgcolor); @@ -2415,7 +2459,6 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { // creation, which causes a resize event and all the associated processing. // The temp window is used to get the DPI. On Wayland no temp window can be // used, so start with window visible unless hidden window requested. - GLFWwindow *common_context = global_state.num_os_windows ? global_state.os_windows[0].handle : NULL; GLFWwindow *temp_window = NULL; glfwWindowHint(GLFW_VISIBLE, window_state != WINDOW_HIDDEN && global_state.is_wayland); float xscale, yscale; @@ -2459,7 +2502,7 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { } glfwGetError(NULL); // clear any stale error - temp_window = glfwCreateWindow(640, 480, "temp", NULL, common_context, NULL); + temp_window = glfwCreateWindow(640, 480, "temp", NULL, NULL); if (temp_window == NULL) glfw_failure(false); get_window_content_scale(temp_window, &xscale, &yscale, &xdpi, &ydpi); } @@ -2490,7 +2533,7 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { initial_window_size_py_callback = get_window_size; } glfwGetError(NULL); // clear any stale error - GLFWwindow *glfw_window = glfwCreateWindow(width, height, title_utf8, NULL, temp_window ? temp_window : common_context, lsc); + GLFWwindow *glfw_window = glfwCreateWindow(width, height, title_utf8, NULL, lsc); initial_window_size_py_callback = NULL; if (temp_window) { glfwDestroyWindow(temp_window); @@ -2500,15 +2543,35 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { #undef glfw_failure // Set titlebar-only mode before the window becomes visible if (global_state.is_wayland && (OPT(hide_window_decorations) & 2) && glfwWaylandSetTitlebarHidden) { glfwWaylandSetTitlebarHidden(glfw_window, true); } - glfwMakeContextCurrent(glfw_window); + gpu_surface_t gpu_surface; + { + GPUNativeWindow native; + native_window_for_gpu(glfw_window, &native); + int fw = 0, fh = 0; + glfwGetFramebufferSize(glfw_window, &fw, &fh); + gpu_surface = gpu_surface_create(&native, &surface_config, (uint32_t)MAX(1, fw), (uint32_t)MAX(1, fh)); + if (!gpu_surface || !gpu_make_surface_current(gpu_surface)) { + PyErr_Format( + PyExc_OSError, + "Failed to create a GPU surface for the window with error: %s. This usually happens because of old/broken GPU drivers.", + gpu_last_error()); + if (gpu_surface) gpu_surface_destroy(gpu_surface); + glfwDestroyWindow(glfw_window); + return NULL; + } + } + glfwSetNativeSurfaceChangedCallback(glfw_window, native_surface_changed_callback); if (is_first_window) initialize_gpu(); bool is_semi_transparent = glfwGetWindowAttrib(glfw_window, GLFW_TRANSPARENT_FRAMEBUFFER); // blank the window once so that there is no initial flash of color // changing, in case the background color is not black blank_canvas(is_semi_transparent ? OPT(background_opacity) : 1.0f, OPT(background), true); - apply_swap_interval(-1); + apply_swap_interval(gpu_surface, -1); // On Wayland the initial swap is allowed only after the first XDG configure event - if (glfwAreSwapsAllowed(glfw_window)) glfwSwapBuffers(glfw_window); + if (glfwAreSwapsAllowed(glfw_window)) { + gpu_surface_present(gpu_surface); + glfwWindowContentsPresented(glfw_window); + } glfwSetInputMode(glfw_window, GLFW_LOCK_KEY_MODS, true); PyObject *pret = PyObject_CallFunction(pre_show_callback, "N", native_window_handle(glfw_window)); if (pret == NULL) return NULL; @@ -2542,6 +2605,7 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) { bind_shader_globals_to_current_context(); OSWindow *w = add_os_window(); w->handle = glfw_window; + w->gpu_surface = gpu_surface; w->disallow_title_changes = disallow_override_title; // A fixed title is never synced from the active window, so store it here if (disallow_override_title) w->window_title = Py_NewRef(title); @@ -2678,6 +2742,9 @@ destroy_os_window(OSWindow *w) { // Ensure mouse cursor is visible and reset to default shape, needed on macOS show_mouse_cursor(w->handle); glfwSetCursor(w->handle, NULL); + // The GPU surface must be destroyed before the native window it renders into + if (w->gpu_surface) gpu_surface_destroy(w->gpu_surface); + w->gpu_surface = GPU_NULL_HANDLE; glfwDestroyWindow(w->handle); } w->handle = NULL; @@ -2801,7 +2868,7 @@ glfw_init(PyObject UNUSED *self, PyObject *args) { return NULL; } glfw_is_loaded = true; - err = load_gpu_driver(gpu_driver_path, debug_rendering != 0, glfwGetProcAddress); + err = load_gpu_driver(gpu_driver_path, debug_rendering != 0); if (err) { PyErr_SetString(PyExc_RuntimeError, err); return NULL; @@ -2836,6 +2903,8 @@ glfw_init(PyObject UNUSED *self, PyObject *args) { static PyObject * glfw_terminate(PYNOARG) { cleanup_shader_resources_on_terminate(); + // Must be done before glfwTerminate() closes the connection to the windowing system + if (gpu_driver.driver) gpu_release_native_resources(); for (size_t i = 0; i < arraysz(cursors); i++) { if (cursors[i].is_custom && cursors[i].glfw) { glfwDestroyCursor(cursors[i].glfw); @@ -3300,7 +3369,9 @@ is_mouse_hidden(OSWindow *w) { void swap_window_buffers(OSWindow *os_window) { if (glfwAreSwapsAllowed(os_window->handle)) { - glfwSwapBuffers(os_window->handle); + if (!gpu_surface_present(os_window->gpu_surface)) + log_error("Failed to present the GPU surface of OS Window: %llu with error: %s", os_window->id, gpu_last_error()); + glfwWindowContentsPresented(os_window->handle); os_window->keep_rendering_till_swap = 0; } } @@ -4398,7 +4469,6 @@ init_glfw(PyObject *m) { // --- Error codes ------------------------------------------------------------- ADDC(GLFW_NOT_INITIALIZED); - ADDC(GLFW_NO_CURRENT_CONTEXT); ADDC(GLFW_INVALID_ENUM); ADDC(GLFW_INVALID_VALUE); ADDC(GLFW_OUT_OF_MEMORY); @@ -4417,46 +4487,7 @@ init_glfw(PyObject *m) { ADDC(GLFW_FLOATING); // --- - ADDC(GLFW_RED_BITS); - ADDC(GLFW_GREEN_BITS); - ADDC(GLFW_BLUE_BITS); - ADDC(GLFW_ALPHA_BITS); - ADDC(GLFW_DEPTH_BITS); - ADDC(GLFW_STENCIL_BITS); - ADDC(GLFW_ACCUM_RED_BITS); - ADDC(GLFW_ACCUM_GREEN_BITS); - ADDC(GLFW_ACCUM_BLUE_BITS); - ADDC(GLFW_ACCUM_ALPHA_BITS); - ADDC(GLFW_AUX_BUFFERS); - ADDC(GLFW_STEREO); - ADDC(GLFW_SAMPLES); - ADDC(GLFW_SRGB_CAPABLE); ADDC(GLFW_REFRESH_RATE); - ADDC(GLFW_DOUBLEBUFFER); - - // --- - ADDC(GLFW_CLIENT_API); - ADDC(GLFW_CONTEXT_VERSION_MAJOR); - ADDC(GLFW_CONTEXT_VERSION_MINOR); - ADDC(GLFW_CONTEXT_REVISION); - ADDC(GLFW_CONTEXT_ROBUSTNESS); - ADDC(GLFW_OPENGL_FORWARD_COMPAT); - ADDC(GLFW_CONTEXT_DEBUG); - ADDC(GLFW_OPENGL_PROFILE); - - // --- - ADDC(GLFW_OPENGL_API); - ADDC(GLFW_OPENGL_ES_API); - - // --- - ADDC(GLFW_NO_ROBUSTNESS); - ADDC(GLFW_NO_RESET_NOTIFICATION); - ADDC(GLFW_LOSE_CONTEXT_ON_RESET); - - // --- - ADDC(GLFW_OPENGL_ANY_PROFILE); - ADDC(GLFW_OPENGL_CORE_PROFILE); - ADDC(GLFW_OPENGL_COMPAT_PROFILE); // --- ADDC(GLFW_CURSOR); diff --git a/kitty/gpu.c b/kitty/gpu.c index 6d8418522..93476bbf7 100644 --- a/kitty/gpu.c +++ b/kitty/gpu.c @@ -30,8 +30,18 @@ driver_fatal(const char *msg) { fatal("%s", msg); } +static void +driver_x11_push_error_trap(void) { + if (glfwX11PushErrorTrap_impl) glfwX11PushErrorTrap(); +} + +static int +driver_x11_pop_error_trap(void) { + return glfwX11PopErrorTrap_impl ? glfwX11PopErrorTrap() : 0; +} + const char * -load_gpu_driver(const char *path, bool debug_rendering, gpu_get_proc_address_func get_proc_address) { +load_gpu_driver(const char *path, bool debug_rendering) { static char errbuf[2048]; if (gpu_driver.driver) return NULL; void *handle = dlopen(path, RTLD_LAZY | RTLD_LOCAL); @@ -48,11 +58,12 @@ load_gpu_driver(const char *path, bool debug_rendering, gpu_get_proc_address_fun return errbuf; } const GPUDriverInitParams params = { - .get_proc_address = get_proc_address, .debug_rendering = debug_rendering, .log_error = driver_log_error, .debug_print = driver_debug_print, .fatal = driver_fatal, + .x11_push_error_trap = driver_x11_push_error_trap, + .x11_pop_error_trap = driver_x11_pop_error_trap, }; GPUDriverAPI api = {0}; void *driver = NULL; diff --git a/kitty/gpu.h b/kitty/gpu.h index dfe86f16a..7ae1d51bd 100644 --- a/kitty/gpu.h +++ b/kitty/gpu.h @@ -24,8 +24,9 @@ typedef struct GPUDriver { extern GPUDriver gpu_driver; // Load the GPU driver shared library at path. Returns NULL on success or an error message. -const char *load_gpu_driver(const char *path, bool debug_rendering, gpu_get_proc_address_func get_proc_address); -// Must be called once a context is current, before any other GPU functions are used +const char *load_gpu_driver(const char *path, bool debug_rendering); +// Must be called once a surface has been created and made current, before any +// other GPU functions, except the surface functions, are used void initialize_gpu_driver(void); void unload_gpu_driver(void); @@ -48,6 +49,61 @@ gpu_get_capabilities(GPUCapabilities *ans) { A.get_capabilities(D, ans); } +static inline bool +gpu_choose_native_visual(const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint64_t *visual_id) { + return A.choose_native_visual(D, native, config, visual_id); +} + +static inline gpu_surface_t +gpu_surface_create(const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint32_t width, uint32_t height) { + return A.surface_create(D, native, config, width, height); +} + +static inline void +gpu_surface_destroy(gpu_surface_t surface) { + A.surface_destroy(D, surface); +} + +static inline bool +gpu_make_surface_current(gpu_surface_t surface) { + return A.make_surface_current(D, surface); +} + +static inline gpu_surface_t +gpu_get_current_surface(void) { + return A.get_current_surface(D); +} + +static inline void +gpu_surface_resize(gpu_surface_t surface, uint32_t width, uint32_t height) { + A.surface_resize(D, surface, width, height); +} + +static inline bool +gpu_surface_present(gpu_surface_t surface) { + return A.surface_present(D, surface); +} + +static inline void +gpu_surface_set_swap_interval(gpu_surface_t surface, int interval) { + A.surface_set_swap_interval(D, surface, interval); +} + +static inline void +gpu_surface_native_changed(gpu_surface_t surface) { + A.surface_native_changed(D, surface); +} + +static inline bool +gpu_surface_recreate(gpu_surface_t surface) { + return A.surface_recreate(D, surface); +} + +static inline void +gpu_release_native_resources(void) { + A.release_native_resources(D); +} + static inline gpu_texture_t gpu_texture_create(const GPUTextureDesc *desc, const GPUPixelData *initial) { return A.texture_create(D, desc, initial); diff --git a/kitty/state.h b/kitty/state.h index 82a493f22..289a0baaf 100644 --- a/kitty/state.h +++ b/kitty/state.h @@ -580,6 +580,7 @@ typedef uint64_t ShaderAnimEventMask; typedef struct OSWindow { void *handle; + gpu_surface_t gpu_surface; id_type id; monotonic_t created_at; struct { @@ -794,7 +795,7 @@ void initialize_gpu(void); void free_vao(ssize_t vao_idx); void cleanup_shader_resources_on_terminate(void); bool remove_os_window(id_type os_window_id); -void *make_os_window_context_current(OSWindow *w); +gpu_surface_t make_os_window_context_current(OSWindow *w); void set_os_window_size(OSWindow *os_window, int x, int y); void get_os_window_size(OSWindow *os_window, int *w, int *h, int *fw, int *fh); void get_os_window_pos(OSWindow *os_window, int *x, int *y); diff --git a/setup.py b/setup.py index bfb30285f..bc729900f 100755 --- a/setup.py +++ b/setup.py @@ -693,7 +693,7 @@ def init_env( raise SystemExit(f'Cannot have quotes in library paths: {val}') library_paths.setdefault(which, []).append(f'{name}="{val}"') - add_lpath('glfw/egl_context.c', '_GLFW_EGL_LIBRARY', egl_library) + add_lpath('gpu/opengl/egl.c', '_GLFW_EGL_LIBRARY', egl_library) add_lpath('kitty/desktop.c', '_KITTY_STARTUP_NOTIFICATION_LIBRARY', startup_notification_library) add_lpath('kitty/desktop.c', '_KITTY_CANBERRA_LIBRARY', canberra_library) add_lpath('kitty/systemd.c', '_KITTY_SYSTEMD_LIBRARY', systemd_library) @@ -1314,17 +1314,30 @@ def gpu_driver_init_env(env: Env, driver: str = 'opengl') -> Env: # Apple deprecated OpenGL in Mojave (10.14) silence the endless # warnings about it ans.cppflags.append('-DGL_SILENCE_DEPRECATION') - ans.ldpaths.extend(('-framework', 'OpenGL')) - # On other platforms the OpenGL functions are loaded at runtime using - # the get_proc_address() function passed in by kitty, so there is no - # need to link against libGL + for f_ in ('OpenGL', 'Cocoa'): + ans.ldpaths.extend(('-framework', f_)) + else: + # The X11 headers are needed for GLX. All libraries, libGL, libEGL, + # libX11, etc. are loaded at runtime, so as to work on both X11 + # and Wayland without any link time dependencies. + for dep in ('x11', 'xrender'): + ans.cflags.extend(pkg_config(dep, '--cflags-only-I')) + ans.ldpaths.append('-ldl') return ans +def gpu_driver_sources(driver: str) -> List[str]: + if driver == 'opengl': + common = ['driver.c', 'gl-wrapper.c'] + platform = ['nsgl.m'] if is_macos else ['egl.c', 'glx.c'] + return [f'gpu/{driver}/{x}' for x in common + platform] + raise KeyError(f'Unknown GPU driver: {driver}') + + def compile_gpu_drivers(compilation_database: CompilationDatabase, build_dsym: bool = False) -> None: for driver in ('opengl',): denv = gpu_driver_init_env(env, driver) - sources = sorted(glob.glob(f'gpu/{driver}/*.c')) + sources = gpu_driver_sources(driver) headers = sorted(set(glob.glob(f'gpu/{driver}/*.h') + gpu_api_headers())) compile_c_extension(denv, f'kitty/{driver}', compilation_database, sources, headers, desc_prefix=f'[{driver}] ', build_dsym=build_dsym)