From ae69df7c69a085f9704afdfa15659dea3c079a9e Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Tue, 3 Nov 2026 08:59:36 +0530 Subject: [PATCH] Move the kitty OpenGL code into a dynamically loaded GPU driver All OpenGL calls now live in gpu/opengl, which is built as kitty/opengl.so, next to the glfw backends. glfw_init() is passed the path to the driver and loads it. The driver is initialized once the first OpenGL context is current. fast_data_types no longer links against libGL. kitty/gpu.c contains the driver loader and the higher level helpers (programs and their metadata, vertex array objects, viewport stack) that were previously in kitty/gl.c, implemented on top of the driver API. shaders.c and the rest of kitty use only the driver API. Also remove the unused GL_* constants and the unused bind_program, create_vao, etc. functions exported to Python. --- .clang-format-ignore | 2 +- .gitattributes | 2 +- gen/srgb_lut.py | 2 +- glad/generate.py | 2 +- gpu/opengl/driver.c | 1056 ++++++++++++++++++++++++++ {kitty => gpu/opengl}/gl-wrapper.c | 0 {kitty => gpu/opengl}/gl-wrapper.h | 0 gpu/opengl/version.h | 17 + kitty/child-monitor.c | 1 + kitty/constants.py | 5 + kitty/data-types.h | 8 +- kitty/fast_data_types.pyi | 9 +- kitty/gl.c | 740 ------------------ kitty/gl.h | 100 --- kitty/glfw.c | 10 +- kitty/gpu.c | 531 +++++++++++++ kitty/gpu.h | 383 ++++++++++ kitty/graphics.c | 7 +- kitty/graphics.h | 8 +- kitty/main.py | 3 +- kitty/shaders.c | 1129 +++++++++++----------------- kitty/srgb_gamma.h | 2 +- kitty/state.c | 1 + kitty/state.h | 37 +- kitty/window_logo.c | 1 + kitty/window_logo.h | 3 +- setup.py | 32 +- 27 files changed, 2526 insertions(+), 1565 deletions(-) create mode 100644 gpu/opengl/driver.c rename {kitty => gpu/opengl}/gl-wrapper.c (100%) rename {kitty => gpu/opengl}/gl-wrapper.h (100%) create mode 100644 gpu/opengl/version.h delete mode 100644 kitty/gl.c delete mode 100644 kitty/gl.h create mode 100644 kitty/gpu.c create mode 100644 kitty/gpu.h diff --git a/.clang-format-ignore b/.clang-format-ignore index b672d67d7..cc8e4c182 100644 --- a/.clang-format-ignore +++ b/.clang-format-ignore @@ -1,6 +1,6 @@ *_generated.* *-generated.* -kitty/gl-wrapper.* +gpu/opengl/gl-wrapper.* kitty/srgb_gamma.* kitty/glfw-wrapper.* kitty/rowcolumn-diacritics.c diff --git a/.gitattributes b/.gitattributes index d2706257f..33e7647ae 100644 --- a/.gitattributes +++ b/.gitattributes @@ -9,7 +9,7 @@ kitty/key_encoding.py linguist-generated=true kitty/rowcolumn-diacritics.c linguist-generated=true kitty/rgb.py linguist-generated=true kitty/srgb_gamma.* linguist-generated=true -kitty/gl-wrapper.* linguist-generated=true +gpu/opengl/gl-wrapper.* linguist-generated=true kitty/glfw-wrapper.* linguist-generated=true kitty/color-names.h linguist-generated=true kitty/parse-graphics-command.h linguist-generated=true diff --git a/gen/srgb_lut.py b/gen/srgb_lut.py index b3d9813d4..7d075c5ef 100755 --- a/gen/srgb_lut.py +++ b/gen/srgb_lut.py @@ -33,7 +33,7 @@ def generate_srgb_lut(line_prefix: str = ' ') -> list[str]: return lines -def generate_srgb_gamma(declaration: str = 'static const GLfloat srgb_lut[256] = {', close: str = '};') -> str: +def generate_srgb_gamma(declaration: str = 'static const float srgb_lut[256] = {', close: str = '};') -> str: lines: list[str] = [] a = lines.append diff --git a/glad/generate.py b/glad/generate.py index 65c522fa0..701624d6b 100755 --- a/glad/generate.py +++ b/glad/generate.py @@ -36,7 +36,7 @@ def export() -> None: data = source.read() data = strip_trailing_whitespace(data) - with open('../kitty/gl-wrapper.h', 'w', encoding='utf-8') as dest: + with open('../gpu/opengl/gl-wrapper.h', 'w', encoding='utf-8') as dest: dest.write(data) diff --git a/gpu/opengl/driver.c b/gpu/opengl/driver.c new file mode 100644 index 000000000..9965929ed --- /dev/null +++ b/gpu/opengl/driver.c @@ -0,0 +1,1056 @@ +/* + * driver.c + * Copyright (C) 2026 Kovid Goyal + * + * Distributed under terms of the GPL3 license. + */ + +// The OpenGL implementation of the kitty GPU driver API, see ../api.h + +#include "../api.h" +#include "version.h" +#include "gl-wrapper.h" +#include +#include +#include +#include + +#define UNUSED __attribute__((unused)) +#define arraysz(x) (sizeof(x) / sizeof(x[0])) +#define MIN(x, y) ((x) < (y) ? (x) : (y)) + +// All texture management (creation, uploads, copies) is done using this unit, +// so that it never disturbs the textures bound to the units used for drawing. +// Drawing never samples from it. OpenGL 3 guarantees at least 16 units. +#define SCRATCH_TEXTURE_UNIT 15 + +typedef struct Texture { + GLuint id; + GLenum target; + GPUTextureDesc desc; +} Texture; + +typedef struct Buffer { + GLuint id; + GLenum target; + size_t size; +} Buffer; + +typedef struct Uniform { + char name[256]; + GLint location; +} Uniform; + +typedef struct Pipeline { + GLuint id; + Uniform *uniforms; + GLint num_uniforms; +} Pipeline; + +typedef struct Driver { + GPUDriverInitParams params; + bool initialized, supports_srgb_output; + int gl_version; + GLint max_texture_size, max_array_texture_layers; + char last_error[8192]; + char version_string[512]; +} Driver; + +// glad's error callback has no user data pointer and there is only ever one +// driver per process +static Driver *the_driver = NULL; + +// Utilities {{{ +#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_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)) + +static void set_error(Driver *d, const char *fmt, ...) __attribute__((format(printf, 2, 3))); + +static void +set_error(Driver *d, const char *fmt, ...) { + va_list ap; + va_start(ap, fmt); + vsnprintf(d->last_error, sizeof(d->last_error), fmt, ap); + va_end(ap); +} + +static void fatal(Driver *d, const char *fmt, ...) __attribute__((format(printf, 2, 3), noreturn)); + +static void +fatal(Driver *d, const char *fmt, ...) { + char buf[4096]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + d->params.fatal(buf); + abort(); // fatal() must not return +} + +static void log_error(Driver *d, const char *fmt, ...) __attribute__((format(printf, 2, 3))); + +static void +log_error(Driver *d, const char *fmt, ...) { + char buf[4096]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + d->params.log_error(buf); +} + +static void +discard_pending_gl_errors(void) { + // glad's error checking callback is installed only with --debug-rendering, + // so in normal runs errors queue up silently. Drain the queue so that a + // subsequent glGetError() reports only what we are interested in. + for (unsigned i = 0; i < 16 && glGetError() != GL_NO_ERROR; i++); +} + +static void +check_for_gl_error(void UNUSED *ret, const char *name, GLADapiproc UNUSED funcptr, int UNUSED len_args, ...) { +#define f(msg) \ + fatal(the_driver, "OpenGL error: %s (calling function: %s)", msg, name); \ + break; + GLenum code = glad_glGetError(); + switch (code) { + case GL_NO_ERROR: break; + case GL_INVALID_ENUM: f("An enum value is invalid (GL_INVALID_ENUM)"); + case GL_INVALID_VALUE: f("An numeric value is invalid (GL_INVALID_VALUE)"); + case GL_INVALID_OPERATION: f("This operation is invalid (GL_INVALID_OPERATION)"); + case GL_INVALID_FRAMEBUFFER_OPERATION: f("The framebuffer object is not complete (GL_INVALID_FRAMEBUFFER_OPERATION)"); + case GL_OUT_OF_MEMORY: f("There is not enough memory left to execute the command. (GL_OUT_OF_MEMORY)"); + case GL_STACK_UNDERFLOW: f("An attempt has been made to perform an operation that would cause an internal stack to underflow. (GL_STACK_UNDERFLOW)"); + case GL_STACK_OVERFLOW: f("An attempt has been made to perform an operation that would cause an internal stack to overflow. (GL_STACK_OVERFLOW)"); + default: fatal(the_driver, "An unknown OpenGL error occurred with code: %d (calling function: %s)", code, name); break; + } +#undef f +} +// }}} + +// Lifecycle {{{ +static const char * +last_error(void *driver) { + return ((Driver *)driver)->last_error; +} + +static const char * +version_string(void *driver) { + Driver *d = driver; + if (!d->initialized) return ""; + int gl_major = GLAD_VERSION_MAJOR(d->gl_version); + int gl_minor = GLAD_VERSION_MINOR(d->gl_version); + const char *gvs = (const char *)glGetString(GL_VERSION); + snprintf(d->version_string, sizeof(d->version_string), "'%s' Detected version: %d.%d", gvs, gl_major, gl_minor); + return d->version_string; +} + +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->gl_version) { + set_error(d, "Loading the OpenGL library failed"); + return false; + } + if (!d->params.debug_rendering) gladUninstallGLDebug(); + gladSetGLPostCallback(check_for_gl_error); + if (!GLAD_GL_ARB_texture_storage) { + set_error(d, "The OpenGL driver on this system is missing the required extension: ARB_texture_storage"); + return false; + } +#ifdef __APPLE__ + // See nsgl_context.m srgb is always supported on macOS but its OpenGL + // drivers dont report the extensions, so hardcode to true. + d->supports_srgb_output = true; +#else + d->supports_srgb_output = (GLAD_GL_ARB_framebuffer_sRGB + GLAD_GL_EXT_framebuffer_sRGB) != 0; +#endif + d->initialized = true; + int gl_major = GLAD_VERSION_MAJOR(d->gl_version); + int gl_minor = GLAD_VERSION_MINOR(d->gl_version); + if (d->params.debug_rendering) { + char buf[1024]; + snprintf(buf, sizeof(buf), "GL version string: %s", version_string(d)); + d->params.debug_print(buf); + } + if (gl_major < OPENGL_REQUIRED_VERSION_MAJOR || (gl_major == OPENGL_REQUIRED_VERSION_MAJOR && gl_minor < OPENGL_REQUIRED_VERSION_MINOR)) { + set_error( + d, + "OpenGL version is %d.%d, version >= %d.%d required for kitty", + gl_major, + gl_minor, + OPENGL_REQUIRED_VERSION_MAJOR, + OPENGL_REQUIRED_VERSION_MINOR); + d->initialized = false; + return false; + } + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &d->max_texture_size); + glGetIntegerv(GL_MAX_ARRAY_TEXTURE_LAYERS, &d->max_array_texture_layers); +#ifdef __APPLE__ + // Since on Apple we could have multiple GPUs, with different capabilities, + // upper bound the values according to the data from https://developer.apple.com/graphicsimaging/opengl/capabilities/ + d->max_texture_size = MIN(8192, d->max_texture_size); + d->max_array_texture_layers = MIN(512, d->max_array_texture_layers); +#endif + return true; +} + +static void +destroy(void *driver) { + if (the_driver == driver) the_driver = NULL; + free(driver); +} + +static void +get_capabilities(void *driver, GPUCapabilities *ans) { + Driver *d = driver; + ans->max_texture_size = d->max_texture_size > 0 ? (uint32_t)d->max_texture_size : 0; + ans->max_array_texture_layers = d->max_array_texture_layers > 0 ? (uint32_t)d->max_array_texture_layers : 0; + ans->supports_srgb_output = d->supports_srgb_output; +} +// }}} + +// Textures {{{ +static bool +format_is_integer(GPUTextureFormat f) { + switch (f) { + case GPU_FORMAT_R8UI: + case GPU_FORMAT_RG8UI: + case GPU_FORMAT_R32UI: return true; + case GPU_FORMAT_R8: + case GPU_FORMAT_RGBA8: + case GPU_FORMAT_SRGB8_ALPHA8: + case GPU_FORMAT_RGBA16: return false; + } + return false; +} + +// The internal format used for mutable (glTexImage) textures. Unsized formats +// are used where possible to let the driver pick the most efficient storage. +static GLint +unsized_internal_format(GPUTextureFormat f) { + switch (f) { + case GPU_FORMAT_R8: return GL_RED; + case GPU_FORMAT_R8UI: return GL_R8UI; + case GPU_FORMAT_RG8UI: return GL_RG8UI; + case GPU_FORMAT_R32UI: return GL_R32UI; + case GPU_FORMAT_RGBA8: return GL_RGBA; + case GPU_FORMAT_SRGB8_ALPHA8: return GL_SRGB_ALPHA; + case GPU_FORMAT_RGBA16: return GL_RGBA16; + } + return GL_RGBA; +} + +// The internal format used for immutable (glTexStorage) textures +static GLenum +sized_internal_format(GPUTextureFormat f) { + switch (f) { + case GPU_FORMAT_R8: return GL_R8; + case GPU_FORMAT_R8UI: return GL_R8UI; + case GPU_FORMAT_RG8UI: return GL_RG8UI; + case GPU_FORMAT_R32UI: return GL_R32UI; + case GPU_FORMAT_RGBA8: return GL_RGBA8; + case GPU_FORMAT_SRGB8_ALPHA8: return GL_SRGB8_ALPHA8; + case GPU_FORMAT_RGBA16: return GL_RGBA16; + } + return GL_RGBA8; +} + +// The pixel transfer format and type used when no pixel data is supplied +static void +default_transfer_format(GPUTextureFormat f, GLenum *format, GLenum *type) { + switch (f) { + case GPU_FORMAT_R8: + *format = GL_RED; + *type = GL_UNSIGNED_BYTE; + return; + case GPU_FORMAT_R8UI: + *format = GL_RED_INTEGER; + *type = GL_UNSIGNED_BYTE; + return; + case GPU_FORMAT_RG8UI: + *format = GL_RG_INTEGER; + *type = GL_UNSIGNED_BYTE; + return; + case GPU_FORMAT_R32UI: + *format = GL_RED_INTEGER; + *type = GL_UNSIGNED_INT; + return; + case GPU_FORMAT_RGBA8: + case GPU_FORMAT_SRGB8_ALPHA8: + case GPU_FORMAT_RGBA16: + *format = GL_RGBA; + *type = GL_UNSIGNED_BYTE; + return; + } + *format = GL_RGBA; + *type = GL_UNSIGNED_BYTE; +} + +static void +transfer_format(GPUTextureFormat tf, GPUPixelLayout layout, GLenum *format, GLenum *type) { + const bool integer = format_is_integer(tf); + switch (layout) { + case GPU_PIXELS_R8: + *format = integer ? GL_RED_INTEGER : GL_RED; + *type = GL_UNSIGNED_BYTE; + return; + case GPU_PIXELS_RG8: + *format = integer ? GL_RG_INTEGER : GL_RG; + *type = GL_UNSIGNED_BYTE; + return; + case GPU_PIXELS_RGB8: + *format = GL_RGB; + *type = GL_UNSIGNED_BYTE; + return; + case GPU_PIXELS_RGBA8: + *format = GL_RGBA; + *type = GL_UNSIGNED_BYTE; + return; + case GPU_PIXELS_RGBA8_PACKED: + *format = GL_RGBA; + *type = GL_UNSIGNED_INT_8_8_8_8; + return; + case GPU_PIXELS_R32UI: + *format = GL_RED_INTEGER; + *type = GL_UNSIGNED_INT; + return; + } + default_transfer_format(tf, format, type); +} + +static GLint +gl_wrap(GPUWrap w) { + switch (w) { + case GPU_WRAP_CLAMP_TO_EDGE: return GL_CLAMP_TO_EDGE; + case GPU_WRAP_CLAMP_TO_BORDER: return GL_CLAMP_TO_BORDER; + case GPU_WRAP_REPEAT: return GL_REPEAT; + case GPU_WRAP_MIRRORED_REPEAT: return GL_MIRRORED_REPEAT; + } + return GL_CLAMP_TO_EDGE; +} + +static void +bind_for_management(const Texture *t) { + glActiveTexture(GL_TEXTURE0 + SCRATCH_TEXTURE_UNIT); + glBindTexture(t->target, t->id); +} + +static void +set_unpack_alignment(const GPUPixelData *p) { + glPixelStorei(GL_UNPACK_ALIGNMENT, p && p->row_alignment ? (GLint)p->row_alignment : 4); +} + +static void +define_texture_storage(Texture *t, const GPUPixelData *initial) { + const GPUTextureDesc *desc = &t->desc; + bind_for_management(t); + const GLint filter = desc->filter == GPU_FILTER_LINEAR ? GL_LINEAR : GL_NEAREST; + glTexParameteri(t->target, GL_TEXTURE_MIN_FILTER, filter); + glTexParameteri(t->target, GL_TEXTURE_MAG_FILTER, filter); + if (desc->wrap == GPU_WRAP_CLAMP_TO_BORDER) { + static const GLfloat border_color[4] = {0}; + glTexParameterfv(t->target, GL_TEXTURE_BORDER_COLOR, border_color); + } + const GLint wrap = gl_wrap(desc->wrap); + glTexParameteri(t->target, GL_TEXTURE_WRAP_S, wrap); + glTexParameteri(t->target, GL_TEXTURE_WRAP_T, wrap); + GLenum format, type; + if (initial) transfer_format(desc->format, initial->layout, &format, &type); + else default_transfer_format(desc->format, &format, &type); + set_unpack_alignment(initial); + if (t->target == GL_TEXTURE_2D_ARRAY) { + glTexStorage3D(t->target, 1, sized_internal_format(desc->format), desc->width, desc->height, desc->layers); + if (initial) glTexSubImage3D(t->target, 0, 0, 0, 0, desc->width, desc->height, desc->layers, format, type, initial->data); + } else { + glTexImage2D(t->target, 0, unsized_internal_format(desc->format), desc->width, desc->height, 0, format, type, initial ? initial->data : NULL); + } +} + +static gpu_texture_t +texture_create(void *driver, const GPUTextureDesc *desc, const GPUPixelData *initial) { + Driver *d = driver; + Texture *t = calloc(1, sizeof(Texture)); + if (!t) { + set_error(d, "Out of memory allocating a texture"); + return GPU_NULL_HANDLE; + } + t->desc = *desc; + if (t->desc.kind != GPU_TEXTURE_2D_ARRAY) t->desc.layers = 1; + t->target = desc->kind == GPU_TEXTURE_2D_ARRAY ? GL_TEXTURE_2D_ARRAY : GL_TEXTURE_2D; + glGenTextures(1, &t->id); + define_texture_storage(t, initial); + return AS_HANDLE(t); +} + +static bool +texture_reset(void *driver UNUSED, gpu_texture_t texture, const GPUTextureDesc *desc, const GPUPixelData *initial) { + Texture *t = AS_TEXTURE(texture); + const GLenum target = desc->kind == GPU_TEXTURE_2D_ARRAY ? GL_TEXTURE_2D_ARRAY : GL_TEXTURE_2D; + // Textures with immutable storage, or that change type, need a new name + if (target == GL_TEXTURE_2D_ARRAY || target != t->target) { + glDeleteTextures(1, &t->id); + glGenTextures(1, &t->id); + } + t->target = target; + t->desc = *desc; + if (t->desc.kind != GPU_TEXTURE_2D_ARRAY) t->desc.layers = 1; + define_texture_storage(t, initial); + return true; +} + +static void +texture_destroy(void *driver UNUSED, gpu_texture_t texture) { + Texture *t = AS_TEXTURE(texture); + if (!t) return; + glDeleteTextures(1, &t->id); + free(t); +} + +static void +texture_upload( + void *driver UNUSED, gpu_texture_t texture, uint32_t x, uint32_t y, uint32_t layer, uint32_t width, uint32_t height, const GPUPixelData *pixels) { + Texture *t = AS_TEXTURE(texture); + bind_for_management(t); + set_unpack_alignment(pixels); + GLenum format, type; + transfer_format(t->desc.format, pixels->layout, &format, &type); + if (t->target == GL_TEXTURE_2D_ARRAY) glTexSubImage3D(t->target, 0, x, y, layer, width, height, 1, format, type, pixels->data); + else glTexSubImage2D(t->target, 0, x, y, width, height, format, type, pixels->data); +} + +static bool +copy_texture_via_framebuffer(const Texture *src, const Texture *dst) { + const GLint width = src->desc.width, height = src->desc.height, layers = src->desc.layers; + GLint prev_read_fbo; + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &prev_read_fbo); + discard_pending_gl_errors(); + GLuint fbo; + glGenFramebuffers(1, &fbo); + glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo); + bind_for_management(dst); + bool ok = true; + for (GLint z = 0; z < layers && ok; z++) { + if (src->target == GL_TEXTURE_2D_ARRAY) glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, src->id, 0, z); + else glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, src->id, 0); + ok = glCheckFramebufferStatus(GL_READ_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; + if (!ok) break; + if (dst->target == GL_TEXTURE_2D_ARRAY) glCopyTexSubImage3D(dst->target, 0, 0, 0, z, 0, 0, width, height); + else glCopyTexSubImage2D(dst->target, 0, 0, 0, 0, 0, width, height); + // A complete framebuffer does not mean the copy itself was accepted, + // for instance if the two internal formats are not copy compatible. + // Without this check we would claim success and leave the new texture + // blank, losing all its contents. + ok = glGetError() == GL_NO_ERROR; + } + glBindFramebuffer(GL_READ_FRAMEBUFFER, prev_read_fbo); + glDeleteFramebuffers(1, &fbo); + return ok; +} + +static void +texture_copy(void *driver, gpu_texture_t src_handle, gpu_texture_t dst_handle) { + // Assumes textures are 32bits per pixel + Driver *d = driver; + const Texture *src = AS_TEXTURE(src_handle), *dst = AS_TEXTURE(dst_handle); + const GLint width = src->desc.width, height = src->desc.height, layers = src->desc.layers; + if (GLAD_GL_ARB_copy_image) { + glCopyImageSubData(src->id, src->target, 0, 0, 0, 0, dst->id, dst->target, 0, 0, 0, 0, width, height, layers); + return; + } + if (copy_texture_via_framebuffer(src, dst)) return; + + static bool copy_image_warned = false; + // Neither ARB_copy_image nor a framebuffer copy is usable, do a slow roundtrip copy + if (!copy_image_warned) { + copy_image_warned = true; + log_error(d, "WARNING: Your system's OpenGL implementation cannot copy between textures on the GPU, falling back to a slower implementation"); + } + GLenum format, type; + if (format_is_integer(src->desc.format)) { + format = GL_RED_INTEGER; + type = GL_UNSIGNED_INT; + } else { + format = GL_RGBA; + type = GL_UNSIGNED_INT_8_8_8_8; + } + uint8_t *pixels = malloc((size_t)width * height * layers * 4u); + if (!pixels) fatal(d, "Out of memory"); + bind_for_management(src); + glPixelStorei(GL_PACK_ALIGNMENT, 4); + glGetTexImage(src->target, 0, format, type, pixels); + bind_for_management(dst); + glPixelStorei(GL_UNPACK_ALIGNMENT, 4); + if (dst->target == GL_TEXTURE_2D_ARRAY) glTexSubImage3D(dst->target, 0, 0, 0, 0, width, height, layers, format, type, pixels); + else glTexSubImage2D(dst->target, 0, 0, 0, width, height, format, type, pixels); + free(pixels); +} + +static bool +texture_read(void *driver, gpu_texture_t texture, GPUPixelLayout layout, void *dst, size_t dst_size) { + Driver *d = driver; + const Texture *t = AS_TEXTURE(texture); + if (layout != GPU_PIXELS_RGBA8 || t->target != GL_TEXTURE_2D) { + set_error(d, "Reading back textures is supported only for 2D textures as RGBA8 pixels"); + return false; + } + if (dst_size < (size_t)t->desc.width * t->desc.height * 4u) { + set_error(d, "Buffer too small to read back texture"); + return false; + } + bind_for_management(t); + glPixelStorei(GL_PACK_ALIGNMENT, 4); + glGetTexImage(t->target, 0, GL_RGBA, GL_UNSIGNED_BYTE, dst); + return true; +} + +static void +texture_get_desc(void *driver UNUSED, gpu_texture_t texture, GPUTextureDesc *ans) { + *ans = AS_TEXTURE(texture)->desc; +} + +static void +bind_texture(void *driver UNUSED, uint32_t unit, gpu_texture_t texture) { + glActiveTexture(GL_TEXTURE0 + unit); + const Texture *t = AS_TEXTURE(texture); + if (t) glBindTexture(t->target, t->id); + else glBindTexture(GL_TEXTURE_2D, 0); +} +// }}} + +// Buffers {{{ +static gpu_buffer_t +buffer_create(void *driver, GPUBufferKind kind) { + Buffer *b = calloc(1, sizeof(Buffer)); + if (!b) { + set_error(driver, "Out of memory allocating a buffer"); + return GPU_NULL_HANDLE; + } + b->target = kind == GPU_BUFFER_UNIFORM ? GL_UNIFORM_BUFFER : GL_ARRAY_BUFFER; + glGenBuffers(1, &b->id); + return AS_HANDLE(b); +} + +static void +buffer_destroy(void *driver UNUSED, gpu_buffer_t buffer) { + Buffer *b = AS_BUFFER(buffer); + if (!b) return; + glDeleteBuffers(1, &b->id); + free(b); +} + +static GLenum +gl_usage(GPUUpdateFrequency f) { + switch (f) { + case GPU_UPDATE_RARELY: return GL_STATIC_DRAW; + case GPU_UPDATE_OFTEN: return GL_DYNAMIC_DRAW; + case GPU_UPDATE_EVERY_USE: return GL_STREAM_DRAW; + } + return GL_STATIC_DRAW; +} + +static void +buffer_allocate(void *driver UNUSED, gpu_buffer_t buffer, size_t size, GPUUpdateFrequency frequency) { + Buffer *b = AS_BUFFER(buffer); + if (b->size == size) return; + b->size = size; + glBindBuffer(b->target, b->id); + glBufferData(b->target, size, NULL, gl_usage(frequency)); + glBindBuffer(b->target, 0); +} + +static void * +buffer_map(void *driver UNUSED, gpu_buffer_t buffer, GPUMapMode mode, size_t offset, size_t size) { + Buffer *b = AS_BUFFER(buffer); + glBindBuffer(b->target, b->id); + switch (mode) { + case GPU_MAP_WRITE: return glMapBuffer(b->target, GL_WRITE_ONLY); + case GPU_MAP_WRITE_DISCARD_RANGE: return glMapBufferRange(b->target, offset, size, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT); + case GPU_MAP_WRITE_DISCARD_ALL: return glMapBufferRange(b->target, offset, size, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); + case GPU_MAP_READ: return glMapBuffer(b->target, GL_READ_ONLY); + } + return NULL; +} + +static void +buffer_unmap(void *driver UNUSED, gpu_buffer_t buffer) { + Buffer *b = AS_BUFFER(buffer); + glBindBuffer(b->target, b->id); + glUnmapBuffer(b->target); + glBindBuffer(b->target, 0); +} + +static void +buffer_copy(void *driver UNUSED, gpu_buffer_t src, size_t src_offset, gpu_buffer_t dst, size_t dst_offset, size_t size) { + glBindBuffer(GL_COPY_READ_BUFFER, AS_BUFFER(src)->id); + glBindBuffer(GL_COPY_WRITE_BUFFER, AS_BUFFER(dst)->id); + glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, src_offset, dst_offset, size); + glBindBuffer(GL_COPY_READ_BUFFER, 0); + glBindBuffer(GL_COPY_WRITE_BUFFER, 0); +} + +static void +bind_uniform_buffer(void *driver UNUSED, uint32_t binding_point, gpu_buffer_t buffer) { + glBindBufferBase(GL_UNIFORM_BUFFER, binding_point, AS_BUFFER(buffer)->id); +} +// }}} + +// Pipelines {{{ +static GLuint +compile_shader(Driver *d, const GPUShaderSource *src) { + GLenum shader_type = src->stage == GPU_SHADER_VERTEX ? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER; + const char *shader_type_name = src->stage == GPU_SHADER_VERTEX ? "vertex" : "fragment"; + if (src->language != GPU_SHADER_LANGUAGE_GLSL) { + set_error(d, "The OpenGL driver supports only GLSL shaders"); + return 0; + } + GLuint shader_id = glCreateShader(shader_type); + const GLchar *code = src->code; + const GLint len = (GLint)(src->size ? src->size : strlen(src->code)); + glShaderSource(shader_id, 1, &code, &len); + glCompileShader(shader_id); + GLint ret = GL_FALSE; + glGetShaderiv(shader_id, GL_COMPILE_STATUS, &ret); + if (ret != GL_TRUE) { + GLsizei loglen; + static char glbuf[4096]; + glGetShaderInfoLog(shader_id, sizeof(glbuf), &loglen, glbuf); + glDeleteShader(shader_id); + set_error(d, "Failed to compile GLSL %s shader:\n%s", shader_type_name, glbuf); + return 0; + } + return shader_id; +} + +static void +pipeline_destroy(void *driver UNUSED, gpu_pipeline_t pipeline) { + Pipeline *p = AS_PIPELINE(pipeline); + if (!p) return; + if (p->id) glDeleteProgram(p->id); + free(p->uniforms); + free(p); +} + +static bool +read_active_uniforms(Driver *d, Pipeline *p) { + glGetProgramiv(p->id, GL_ACTIVE_UNIFORMS, &p->num_uniforms); + if (p->num_uniforms <= 0) return true; + p->uniforms = calloc(p->num_uniforms, sizeof(Uniform)); + if (!p->uniforms) { + set_error(d, "Out of memory reading the uniforms of a GPU program"); + return false; + } + for (GLint i = 0; i < p->num_uniforms; i++) { + Uniform *u = p->uniforms + i; + GLint size; + GLenum type; + glGetActiveUniform(p->id, (GLuint)i, sizeof(u->name), NULL, &size, &type, u->name); + char *l = strchr(u->name, '['); + if (l) *l = 0; + u->location = glGetUniformLocation(p->id, u->name); + } + return true; +} + +static gpu_pipeline_t +pipeline_create(void *driver, const GPUShaderSource *sources, size_t num_sources) { + Driver *d = driver; + Pipeline *p = calloc(1, sizeof(Pipeline)); + if (!p) { + set_error(d, "Out of memory allocating a GPU program"); + return GPU_NULL_HANDLE; + } + p->id = glCreateProgram(); + for (size_t i = 0; i < num_sources; i++) { + GLuint shader_id = compile_shader(d, sources + i); + if (!shader_id) { + pipeline_destroy(d, AS_HANDLE(p)); + return GPU_NULL_HANDLE; + } + glAttachShader(p->id, shader_id); + glDeleteShader(shader_id); + } + glLinkProgram(p->id); + GLint ret = GL_FALSE; + glGetProgramiv(p->id, GL_LINK_STATUS, &ret); + if (ret != GL_TRUE) { + GLsizei len; + static char glbuf[4096]; + glGetProgramInfoLog(p->id, sizeof(glbuf), &len, glbuf); + set_error(d, "Failed to link GLSL shaders:\n%s", glbuf); + pipeline_destroy(d, AS_HANDLE(p)); + return GPU_NULL_HANDLE; + } + if (!read_active_uniforms(d, p)) { + pipeline_destroy(d, AS_HANDLE(p)); + return GPU_NULL_HANDLE; + } + return AS_HANDLE(p); +} + +static void +use_pipeline(void *driver UNUSED, gpu_pipeline_t pipeline) { + const Pipeline *p = AS_PIPELINE(pipeline); + glUseProgram(p ? p->id : 0); +} + +static int32_t +pipeline_uniform_slot(void *driver UNUSED, gpu_pipeline_t pipeline, const char *name) { + const Pipeline *p = AS_PIPELINE(pipeline); + const size_t n = strlen(name) + 1; + for (GLint i = 0; i < p->num_uniforms; i++) { + const Uniform *u = p->uniforms + i; + if (strncmp(u->name, name, n) == 0) return u->location; + } + return -1; +} + +static bool +pipeline_uniform_block(void *driver, gpu_pipeline_t pipeline, const char *name, GPUUniformBlockInfo *ans) { + const Pipeline *p = AS_PIPELINE(pipeline); + GLuint index = glGetUniformBlockIndex(p->id, name); + if (index == GL_INVALID_INDEX) { + set_error(driver, "Could not find block index for %s", name); + return false; + } + GLint size; + glGetActiveUniformBlockiv(p->id, index, GL_UNIFORM_BLOCK_DATA_SIZE, &size); + ans->index = index; + ans->size = size > 0 ? (uint32_t)size : 0; + return true; +} + +static bool +pipeline_uniform_array(void *driver, gpu_pipeline_t pipeline, const char *name, GPUUniformArrayInfo *ans) { + const Pipeline *p = AS_PIPELINE(pipeline); + const GLchar *names[1] = {name}; + GLuint t; + glGetUniformIndices(p->id, 1, names, &t); + if (t == GL_INVALID_INDEX) { + set_error(driver, "Could not find the index for uniform array: %s", name); + return false; + } + GLint stride, offset, size; + glGetActiveUniformsiv(p->id, 1, &t, GL_UNIFORM_ARRAY_STRIDE, &stride); + glGetActiveUniformsiv(p->id, 1, &t, GL_UNIFORM_OFFSET, &offset); + glGetActiveUniformsiv(p->id, 1, &t, GL_UNIFORM_SIZE, &size); + ans->stride = stride > 0 ? (uint32_t)stride : 0; + ans->offset = offset > 0 ? (uint32_t)offset : 0; + ans->count = size > 0 ? (uint32_t)size : 0; + return true; +} + +static void +pipeline_bind_uniform_block(void *driver UNUSED, gpu_pipeline_t pipeline, uint32_t block_index, uint32_t binding_point) { + glUniformBlockBinding(AS_PIPELINE(pipeline)->id, block_index, binding_point); +} + +static int32_t +pipeline_attribute_location(void *driver UNUSED, gpu_pipeline_t pipeline, const char *name) { + return glGetAttribLocation(AS_PIPELINE(pipeline)->id, name); +} + +static void +set_uniform_floats(void *driver UNUSED, int32_t slot, uint32_t components, uint32_t count, const float *v) { + if (slot < 0) return; + switch (components) { + case 1: glUniform1fv(slot, count, v); break; + case 2: glUniform2fv(slot, count, v); break; + case 3: glUniform3fv(slot, count, v); break; + case 4: glUniform4fv(slot, count, v); break; + } +} + +static void +set_uniform_ints(void *driver UNUSED, int32_t slot, uint32_t components, uint32_t count, const int32_t *v) { + if (slot < 0) return; + switch (components) { + case 1: glUniform1iv(slot, count, v); break; + case 2: glUniform2iv(slot, count, v); break; + case 3: glUniform3iv(slot, count, v); break; + case 4: glUniform4iv(slot, count, v); break; + } +} + +static void +set_uniform_uints(void *driver UNUSED, int32_t slot, uint32_t components, uint32_t count, const uint32_t *v) { + if (slot < 0) return; + switch (components) { + case 1: glUniform1uiv(slot, count, v); break; + case 2: glUniform2uiv(slot, count, v); break; + case 3: glUniform3uiv(slot, count, v); break; + case 4: glUniform4uiv(slot, count, v); break; + } +} +// }}} + +// Vertex layouts {{{ +static gpu_vertex_layout_t +vertex_layout_create(void *driver UNUSED) { + GLuint vao_id; + glGenVertexArrays(1, &vao_id); + return vao_id; +} + +static void +vertex_layout_destroy(void *driver UNUSED, gpu_vertex_layout_t layout) { + GLuint vao_id = AS_GL_NAME(layout); + if (vao_id) glDeleteVertexArrays(1, &vao_id); +} + +static void +bind_vertex_layout(void *driver UNUSED, gpu_vertex_layout_t layout) { + glBindVertexArray(AS_GL_NAME(layout)); +} + +static void +vertex_layout_set_attribute( + void *driver UNUSED, + gpu_vertex_layout_t layout, + uint32_t location, + gpu_buffer_t buffer, + uint32_t components, + GPUAttribType type, + uint32_t stride, + size_t offset, + uint32_t instance_divisor) { + glBindVertexArray(AS_GL_NAME(layout)); + const Buffer *b = AS_BUFFER(buffer); + glBindBuffer(GL_ARRAY_BUFFER, b->id); + glEnableVertexAttribArray(location); + void *ptr = (void *)(uintptr_t)offset; + switch (type) { + case GPU_ATTRIB_U8: glVertexAttribIPointer(location, components, GL_UNSIGNED_BYTE, stride, ptr); break; + case GPU_ATTRIB_U16: glVertexAttribIPointer(location, components, GL_UNSIGNED_SHORT, stride, ptr); break; + case GPU_ATTRIB_U32: glVertexAttribIPointer(location, components, GL_UNSIGNED_INT, stride, ptr); break; + case GPU_ATTRIB_F32: glVertexAttribPointer(location, components, GL_FLOAT, GL_FALSE, stride, ptr); break; + } + glVertexAttribDivisorARB(location, instance_divisor); + glBindBuffer(GL_ARRAY_BUFFER, 0); +} +// }}} + +// Render targets {{{ +static const char * +framebuffer_status_string(GLenum status) { + switch (status) { + case GL_FRAMEBUFFER_COMPLETE: return NULL; + case GL_FRAMEBUFFER_UNDEFINED: return "GL_FRAMEBUFFER_UNDEFINED"; + case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: return "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; + case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: return "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; + case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: return "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"; + case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: return "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"; + case GL_FRAMEBUFFER_UNSUPPORTED: return "GL_FRAMEBUFFER_UNSUPPORTED"; + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: return "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"; + default: return "Unknown error"; + } +} + +typedef struct { + GLint draw, read; +} SavedFramebuffers; + +static SavedFramebuffers +save_framebuffers(void) { + SavedFramebuffers ans; + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &ans.draw); + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &ans.read); + return ans; +} + +static void +restore_framebuffers(SavedFramebuffers s) { + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, s.draw); + glBindFramebuffer(GL_READ_FRAMEBUFFER, s.read); +} + +static gpu_render_target_t +render_target_create(void *driver UNUSED, gpu_texture_t color_texture) { + const Texture *t = AS_TEXTURE(color_texture); + SavedFramebuffers saved = save_framebuffers(); + GLuint fbo; + glGenFramebuffers(1, &fbo); + glBindFramebuffer(GL_FRAMEBUFFER, fbo); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, t->id, 0); + restore_framebuffers(saved); + return fbo; +} + +static void +render_target_destroy(void *driver UNUSED, gpu_render_target_t target) { + GLuint fbo = AS_GL_NAME(target); + if (fbo) glDeleteFramebuffers(1, &fbo); +} + +static void +set_render_target(void *driver UNUSED, gpu_render_target_t target) { + glBindFramebuffer(GL_FRAMEBUFFER, AS_GL_NAME(target)); +} + +static gpu_render_target_t +get_render_target(void *driver UNUSED) { + GLint ans; + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &ans); + return ans > 0 ? (gpu_render_target_t)ans : GPU_NULL_HANDLE; +} + +static const char * +render_target_status(void *driver UNUSED, gpu_render_target_t target) { + GLint current; + glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, ¤t); + if ((GLuint)current == AS_GL_NAME(target)) return framebuffer_status_string(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, AS_GL_NAME(target)); + const char *ans = framebuffer_status_string(glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, current); + return ans; +} + +static void +clear(void *driver UNUSED, float r, float g, float b, float a) { + glClearColor(r, g, b, a); + glClear(GL_COLOR_BUFFER_BIT); +} + +static void +set_viewport(void *driver UNUSED, int32_t x, int32_t y, uint32_t width, uint32_t height) { + glViewport(x, y, width, height); +} + +static void +get_viewport(void *driver UNUSED, int32_t ans[4]) { + glGetIntegerv(GL_VIEWPORT, ans); +} + +static void +set_scissor(void *driver UNUSED, bool enabled, int32_t x, int32_t y, uint32_t width, uint32_t height) { + if (enabled) { + glEnable(GL_SCISSOR_TEST); + glScissor(x, y, width, height); + } else glDisable(GL_SCISSOR_TEST); +} + +static void +set_srgb_output(void *driver UNUSED, bool enabled) { + if (enabled) glEnable(GL_FRAMEBUFFER_SRGB); + else glDisable(GL_FRAMEBUFFER_SRGB); +} + +static void +read_pixels(void *driver UNUSED, int32_t x, int32_t y, uint32_t width, uint32_t height, void *dst) { + glPixelStorei(GL_PACK_ALIGNMENT, 1); + glReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, dst); + glPixelStorei(GL_PACK_ALIGNMENT, 4); +} + +static void +copy_to_texture(void *driver UNUSED, gpu_texture_t dst, int32_t x, int32_t y, uint32_t width, uint32_t height) { + const Texture *t = AS_TEXTURE(dst); + bind_for_management(t); + glCopyTexSubImage2D(t->target, 0, 0, 0, x, y, width, height); +} +// }}} + +// Drawing {{{ +static void +draw_quad(void *driver UNUSED, uint32_t instance_count, GPUBlendMode blend) { + if (blend == GPU_BLEND_PREMULTIPLIED_ALPHA) { + glEnable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } else { + glDisable(GL_BLEND); + glBlendFunc(GL_ONE, GL_ZERO); + } + if (instance_count) glDrawArraysInstanced(GL_TRIANGLE_FAN, 0, 4, instance_count); + else glDrawArrays(GL_TRIANGLE_FAN, 0, 4); +} +// }}} + +__attribute__((visibility("default"))) bool +kitty_gpu_driver_load(uint32_t api_version, const GPUDriverInitParams *params, GPUDriverAPI *api, void **driver, char *errbuf, size_t errbuf_size) { + if (api_version != KITTY_GPU_API_VERSION) { + 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) { + snprintf(errbuf, errbuf_size, "The OpenGL driver was not passed all required callbacks"); + return false; + } + if (the_driver) { + snprintf(errbuf, errbuf_size, "The OpenGL driver has already been loaded"); + return false; + } + Driver *d = calloc(1, sizeof(Driver)); + if (!d) { + snprintf(errbuf, errbuf_size, "Out of memory allocating the OpenGL driver"); + return false; + } + d->params = *params; + the_driver = d; + *api = (GPUDriverAPI){ + .api_version = KITTY_GPU_API_VERSION, +#define F(name) .name = name + F(initialize), + F(destroy), + F(last_error), + F(version_string), + F(get_capabilities), + + F(texture_create), + F(texture_reset), + F(texture_destroy), + F(texture_upload), + F(texture_copy), + F(texture_read), + F(texture_get_desc), + F(bind_texture), + + F(buffer_create), + F(buffer_destroy), + F(buffer_allocate), + F(buffer_map), + F(buffer_unmap), + F(buffer_copy), + F(bind_uniform_buffer), + + F(pipeline_create), + F(pipeline_destroy), + F(use_pipeline), + F(pipeline_uniform_slot), + F(pipeline_uniform_block), + F(pipeline_uniform_array), + F(pipeline_bind_uniform_block), + F(pipeline_attribute_location), + F(set_uniform_floats), + F(set_uniform_ints), + F(set_uniform_uints), + + F(vertex_layout_create), + F(vertex_layout_destroy), + F(bind_vertex_layout), + F(vertex_layout_set_attribute), + + F(render_target_create), + F(render_target_destroy), + F(set_render_target), + F(get_render_target), + F(render_target_status), + F(clear), + F(set_viewport), + F(get_viewport), + F(set_scissor), + F(set_srgb_output), + F(read_pixels), + F(copy_to_texture), + + F(draw_quad), +#undef F + }; + *driver = d; + return true; +} diff --git a/kitty/gl-wrapper.c b/gpu/opengl/gl-wrapper.c similarity index 100% rename from kitty/gl-wrapper.c rename to gpu/opengl/gl-wrapper.c diff --git a/kitty/gl-wrapper.h b/gpu/opengl/gl-wrapper.h similarity index 100% rename from kitty/gl-wrapper.h rename to gpu/opengl/gl-wrapper.h diff --git a/gpu/opengl/version.h b/gpu/opengl/version.h new file mode 100644 index 000000000..40171dba1 --- /dev/null +++ b/gpu/opengl/version.h @@ -0,0 +1,17 @@ +/* + * version.h + * Copyright (C) 2026 Kovid Goyal + * + * Distributed under terms of the GPL3 license. + */ + +#pragma once + +// Required minimum OpenGL version +#define OPENGL_REQUIRED_VERSION_MAJOR 3 +#ifdef __APPLE__ +#define OPENGL_REQUIRED_VERSION_MINOR 3 +#else +#define OPENGL_REQUIRED_VERSION_MINOR 1 +#endif +#define GLSL_VERSION 140 diff --git a/kitty/child-monitor.c b/kitty/child-monitor.c index 1b24da100..25c7579ae 100644 --- a/kitty/child-monitor.c +++ b/kitty/child-monitor.c @@ -8,6 +8,7 @@ #include "loop-utils.h" #include "safe-wrappers.h" #include "state.h" +#include "gpu.h" #include "threading.h" #include "screen.h" #include "monotonic.h" diff --git a/kitty/constants.py b/kitty/constants.py index d2136501a..a8bd4e84b 100644 --- a/kitty/constants.py +++ b/kitty/constants.py @@ -232,6 +232,11 @@ def glfw_path(module: str) -> str: return os.path.join(extensions_dir, f'{prefix}glfw-{module}.so') +def gpu_driver_path(driver: str = 'opengl') -> str: + prefix = 'kitty.' if getattr(sys, 'frozen', False) else '' + return os.path.join(extensions_dir, f'{prefix}{driver}.so') + + def detect_if_wayland_ok() -> bool: if not os.environ.get('WAYLAND_DISPLAY') and not os.environ.get('WAYLAND_SOCKET'): return False diff --git a/kitty/data-types.h b/kitty/data-types.h index 2d4623f5e..2b79649b9 100644 --- a/kitty/data-types.h +++ b/kitty/data-types.h @@ -21,15 +21,11 @@ #include #include "glfw-wrapper.h" #include "banned.h" -// Required minimum OpenGL version -#define OPENGL_REQUIRED_VERSION_MAJOR 3 #ifdef __APPLE__ #include -#define OPENGL_REQUIRED_VERSION_MINOR 3 -#else -#define OPENGL_REQUIRED_VERSION_MINOR 1 #endif -#define GLSL_VERSION 140 +#include "../gpu/opengl/version.h" +#include "../gpu/api.h" #define GLFW_MOD_KITTY (GLFW_MOD_LAST * 2) #define UNUSED __attribute__((unused)) #define PYNOARG PyObject *__a1 UNUSED, PyObject *__a2 UNUSED diff --git a/kitty/fast_data_types.pyi b/kitty/fast_data_types.pyi index 379b70e98..3c07dd32a 100644 --- a/kitty/fast_data_types.pyi +++ b/kitty/fast_data_types.pyi @@ -560,7 +560,7 @@ def add_window(os_window_id: int, tab_id: int, title: str) -> int: def compile_program( which: int, vertex_shaders: Tuple[str, ...], fragment_shaders: Tuple[str, ...], metadata: Dict[str, Any], allow_recompile: bool = False -) -> int: +) -> None: pass def custom_shader_needs_render(before: Tuple[bool, int, int], after: Tuple[bool, int, int], event_mask: int, now: int) -> bool: ... @@ -669,7 +669,12 @@ def glfw_terminate() -> None: pass def glfw_init( - path: str, edge_spacing_func: Callable[[EdgeLiteral], float], debug_keyboard: bool = False, debug_rendering: bool = False, wayland_enable_ime: bool = True + path: str, + gpu_driver_path: str, + edge_spacing_func: Callable[[EdgeLiteral], float], + debug_keyboard: bool = False, + debug_rendering: bool = False, + wayland_enable_ime: bool = True, ) -> tuple[bool, bool]: pass diff --git a/kitty/gl.c b/kitty/gl.c deleted file mode 100644 index 0cd240ede..000000000 --- a/kitty/gl.c +++ /dev/null @@ -1,740 +0,0 @@ -/* - * gl.c - * Copyright (C) 2019 Kovid Goyal - * - * Distributed under terms of the GPL3 license. - */ - -#include "gl.h" -#include -#include -#include "glfw-wrapper.h" -#include "state.h" -#include "png-reader.h" - -// GL setup and error handling {{{ -static void -check_for_gl_error(void UNUSED *ret, const char *name, GLADapiproc UNUSED funcptr, int UNUSED len_args, ...) { -#define f(msg) \ - fatal("OpenGL error: %s (calling function: %s)", msg, name); \ - break; - GLenum code = glad_glGetError(); - switch (code) { - case GL_NO_ERROR: break; - case GL_INVALID_ENUM: f("An enum value is invalid (GL_INVALID_ENUM)"); - case GL_INVALID_VALUE: f("An numeric value is invalid (GL_INVALID_VALUE)"); - case GL_INVALID_OPERATION: f("This operation is invalid (GL_INVALID_OPERATION)"); - case GL_INVALID_FRAMEBUFFER_OPERATION: f("The framebuffer object is not complete (GL_INVALID_FRAMEBUFFER_OPERATION)"); - case GL_OUT_OF_MEMORY: f("There is not enough memory left to execute the command. (GL_OUT_OF_MEMORY)"); - case GL_STACK_UNDERFLOW: f("An attempt has been made to perform an operation that would cause an internal stack to underflow. (GL_STACK_UNDERFLOW)"); - case GL_STACK_OVERFLOW: f("An attempt has been made to perform an operation that would cause an internal stack to overflow. (GL_STACK_OVERFLOW)"); - default: fatal("An unknown OpenGL error occurred with code: %d (calling function: %s)", code, name); break; - } -} - -const char * -gl_version_string(void) { - static char buf[256]; - int gl_major = GLAD_VERSION_MAJOR(global_state.gl_version); - int gl_minor = GLAD_VERSION_MINOR(global_state.gl_version); - const char *gvs = (const char *)glGetString(GL_VERSION); - snprintf(buf, sizeof(buf), "'%s' Detected version: %d.%d", gvs, gl_major, gl_minor); - return buf; -} - -void -gl_init(void) { - static bool glad_loaded = false; - if (!glad_loaded) { - global_state.gl_version = gladLoadGL(glfwGetProcAddress); - if (!global_state.gl_version) { fatal("Loading the OpenGL library failed"); } - if (!global_state.debug_rendering) { gladUninstallGLDebug(); } - gladSetGLPostCallback(check_for_gl_error); -#define ARB_TEST(name) \ - if (!GLAD_GL_ARB_##name) { fatal("The OpenGL driver on this system is missing the required extension: ARB_%s", #name); } - ARB_TEST(texture_storage); -#undef ARB_TEST -#ifdef __APPLE__ - // See nsgl_context.m srgb is always supported on macOS but its OpenGL - // drivers dont report the extensions, so hardcode to true. - global_state.supports_framebuffer_srgb = true; -#else - global_state.supports_framebuffer_srgb = (GLAD_GL_ARB_framebuffer_sRGB + GLAD_GL_EXT_framebuffer_sRGB) != 0; -#endif - glad_loaded = true; - int gl_major = GLAD_VERSION_MAJOR(global_state.gl_version); - int gl_minor = GLAD_VERSION_MINOR(global_state.gl_version); - if (global_state.debug_rendering) printf("[%.3f] GL version string: %s\n", monotonic_t_to_s_double(monotonic()), gl_version_string()); - if (gl_major < OPENGL_REQUIRED_VERSION_MAJOR || (gl_major == OPENGL_REQUIRED_VERSION_MAJOR && gl_minor < OPENGL_REQUIRED_VERSION_MINOR)) { - fatal( - "OpenGL version is %d.%d, version >= %d.%d required for kitty", - gl_major, - gl_minor, - OPENGL_REQUIRED_VERSION_MAJOR, - OPENGL_REQUIRED_VERSION_MINOR); - } - } -} - -const char * -check_framebuffer_status(void) { - GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - switch (status) { - case GL_FRAMEBUFFER_COMPLETE: return NULL; - case GL_FRAMEBUFFER_UNDEFINED: return ("GL_FRAMEBUFFER_UNDEFINED"); - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: return ("GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: return ("GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); - case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: return ("GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"); - case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: return ("GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"); - case GL_FRAMEBUFFER_UNSUPPORTED: return ("GL_FRAMEBUFFER_UNSUPPORTED"); - case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: return ("GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"); - default: return ("Unknown error"); - } -} - -void -free_texture(GLuint *tex_id) { - glDeleteTextures(1, tex_id); - *tex_id = 0; -} - -void -free_framebuffer(GLuint *fb_id) { - glDeleteFramebuffers(1, fb_id); - *fb_id = 0; -} - -static GLuint output_framebuffer = 0; - -void -bind_framebuffer_for_output(unsigned fbid) { - glBindFramebuffer(GL_FRAMEBUFFER, fbid ? fbid : output_framebuffer); -} - -void -set_framebuffer_to_use_for_output(unsigned fbid) { - output_framebuffer = fbid; -} - -static void -set_blending(bool allowed) { - if (allowed) { - glEnable(GL_BLEND); - glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - } // blending of pre-multiplied colors - else { - glDisable(GL_BLEND); - glBlendFunc(GL_ONE, GL_ZERO); - } // no blending -} - -void -draw_quad(bool blend, unsigned instance_count) { - set_blending(blend); - if (instance_count) glDrawArraysInstanced(GL_TRIANGLE_FAN, 0, 4, instance_count); - else glDrawArrays(GL_TRIANGLE_FAN, 0, 4); -} - -static struct { - GLsizei items[16][4]; - size_t used; -} saved_viewports; - -void -set_gpu_viewport(unsigned w, unsigned h) { - glViewport(0, 0, w, h); -} - -Viewport -get_gpu_viewport(void) { - GLsizei v[4]; - glGetIntegerv(GL_VIEWPORT, v); - return (Viewport){.left = v[0], .top = v[1], .width = v[2], .height = v[3]}; -} - -void -save_viewport_using_bottom_left_origin(GLsizei newx, GLsizei newy, GLsizei width, GLsizei height) { - if (saved_viewports.used >= arraysz(saved_viewports.items)) fatal("Too many nested saved viewports"); - GLsizei *saved_viewport = saved_viewports.items[saved_viewports.used++]; - glGetIntegerv(GL_VIEWPORT, saved_viewport); - glViewport(newx, newy, width, height); -} - -void -save_viewport_using_top_left_origin(GLsizei newx, GLsizei newy, GLsizei width, GLsizei height, GLsizei full_framebuffer_height) { - // Converts the viewport defined by the specified arguments which are - // assumed to be in the usual co-ord system with origin at top left to the - // OpenGL viewport co-ord system with origin at bottom left. - // Use restore_viewport() to restore the viewport to what it was before. - if (saved_viewports.used >= arraysz(saved_viewports.items)) fatal("Too many nested saved viewports"); - GLsizei *saved_viewport = saved_viewports.items[saved_viewports.used++]; - glGetIntegerv(GL_VIEWPORT, saved_viewport); - newy = full_framebuffer_height - (newy + height); - glViewport(newx, newy, width, height); -} - -void -restore_viewport(void) { - if (!saved_viewports.used) fatal("Trying to restore a viewport when none is saved"); - GLsizei *saved_viewport = saved_viewports.items[--saved_viewports.used]; - glViewport(saved_viewport[0], saved_viewport[1], saved_viewport[2], saved_viewport[3]); -} - -void -enable_scissor_using_top_left_origin(Viewport vp, unsigned full_framebuffer_height) { - glEnable(GL_SCISSOR_TEST); - GLsizei newy = full_framebuffer_height - (vp.top + vp.height); - glScissor(vp.left, newy, vp.width, vp.height); -} - -void -disable_scissor(void) { - glDisable(GL_SCISSOR_TEST); -} - -static float -linear_to_srgb(float c) { - return (c <= 0.0031308f) ? 12.92f * c : 1.055f * powf(c, 1.0f / 2.4f) - 0.055f; -} - -void -save_texture_as_png(uint32_t texture_id, const char *filename) { - GLint prev_tex = 0; - glGetIntegerv(GL_TEXTURE_BINDING_2D, &prev_tex); - glBindTexture(GL_TEXTURE_2D, texture_id); - int width = 0, height = 0; - glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width); - glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height); - size_t sz = sizeof(uint32_t) * width * height; - uint32_t *data = malloc(sz); - glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); - // assume data is linear and pre-multiplied - for (int i = 0; i < width * height; i++) { - uint32_t px = data[i]; - uint8_t r = (px >> 0) & 0xFF; - uint8_t g = (px >> 8) & 0xFF; - uint8_t b = (px >> 16) & 0xFF; - uint8_t a = (px >> 24) & 0xFF; - float alpha = a / 255.0f; - float rf = 0, gf = 0, bf = 0; - if (alpha > 0.0f) { - rf = (r / 255.0f) / alpha; - gf = (g / 255.0f) / alpha; - bf = (b / 255.0f) / alpha; - } - rf = linear_to_srgb(rf); - gf = linear_to_srgb(gf); - bf = linear_to_srgb(bf); - r = (uint8_t)(rf * 255); - g = (uint8_t)(gf * 255); - b = (uint8_t)(bf * 255); - data[i] = (r << 0) | (g << 8) | (b << 16) | (a << 24); - } - - const char *png = png_from_32bit_rgba((char *)data, width, height, &sz, true); - if (!sz) fatal("Failed to save PNG to %s with error: %s", filename, png); - free(data); - FILE *file = fopen(filename, "wb"); - fwrite(png, 1, sz, file); - fclose(file); - glBindTexture(GL_TEXTURE_2D, prev_tex); -} - - -// }}} - -// Programs {{{ - -static Program programs[64] = {{0}}; - -GLuint -compile_shaders(GLenum shader_type, GLsizei count, const GLchar *const *source) { - GLuint shader_id = glCreateShader(shader_type); - glShaderSource(shader_id, count, source, NULL); - glCompileShader(shader_id); - GLint ret = GL_FALSE; - glGetShaderiv(shader_id, GL_COMPILE_STATUS, &ret); - if (ret != GL_TRUE) { - GLsizei len; - static char glbuf[4096]; - glGetShaderInfoLog(shader_id, sizeof(glbuf), &len, glbuf); - glDeleteShader(shader_id); - const char *shader_type_name = "unknown_type"; - switch (shader_type) { - case GL_VERTEX_SHADER: shader_type_name = "vertex"; break; - case GL_FRAGMENT_SHADER: shader_type_name = "fragment"; break; - } - PyErr_Format(PyExc_ValueError, "Failed to compile GLSL %s shader:\n%s", shader_type_name, glbuf); - return 0; - } - return shader_id; -} - -Program * -program_ptr(int program) { - return programs + (size_t)program; -} - -GLuint -program_id(int program) { - return programs[program].id; -} - - -void -init_uniforms(int program) { - Program *p = programs + program; - glGetProgramiv(p->id, GL_ACTIVE_UNIFORMS, &(p->num_of_uniforms)); - for (GLint i = 0; i < p->num_of_uniforms; i++) { - Uniform *u = p->uniforms + i; - glGetActiveUniform(p->id, (GLuint)i, sizeof(u->name) / sizeof(u->name[0]), NULL, &(u->size), &(u->type), u->name); - char *l = strchr(u->name, '['); - if (l) *l = 0; - u->location = glGetUniformLocation(p->id, u->name); - u->idx = i; - } -} - -GLint -get_uniform_location(int program, const char *name) { - Program *p = programs + program; - const size_t n = strlen(name) + 1; - for (GLint i = 0; i < p->num_of_uniforms; i++) { - Uniform *u = p->uniforms + i; - if (strncmp(u->name, name, n) == 0) return u->location; - } - return -1; -} - -GLint -get_uniform_information(int program, const char *name, GLenum information_type) { - GLint q; - GLuint t; - const char *names[] = {""}; - names[0] = name; - GLuint pid = program_id(program); - glGetUniformIndices(pid, 1, (void *)names, &t); - glGetActiveUniformsiv(pid, 1, &t, information_type, &q); - return q; -} - -ArrayInformation -get_uniform_array_information(int program, const char *name) { - ArrayInformation ans; - const char *names[] = {""}; - names[0] = name; - GLuint pid = program_id(program); - GLuint t; - glGetUniformIndices(pid, 1, (void *)names, &t); - if (t == GL_INVALID_INDEX) { fatal("Could not find the index for uniform array: %s", name); } - glGetActiveUniformsiv(pid, 1, &t, GL_UNIFORM_ARRAY_STRIDE, &ans.stride); - glGetActiveUniformsiv(pid, 1, &t, GL_UNIFORM_OFFSET, &ans.offset); - glGetActiveUniformsiv(pid, 1, &t, GL_UNIFORM_SIZE, &ans.size); - return ans; -} - -GLint -attrib_location(int program, const char *name) { - GLint ans = glGetAttribLocation(programs[program].id, name); - return ans; -} - -GLuint -block_index(int program, const char *name) { - GLuint ans = glGetUniformBlockIndex(programs[program].id, name); - if (ans == GL_INVALID_INDEX) { fatal("Could not find block index for %s", name); } - return ans; -} - - -GLint -block_size(int program, GLuint block_index) { - GLint ans; - glGetActiveUniformBlockiv(programs[program].id, block_index, GL_UNIFORM_BLOCK_DATA_SIZE, &ans); - return ans; -} - -// Program metadata (uniform/attribute locations and UBO/array info, looked up by name) {{{ -#define NAME program_metadata_map -#define KEY_TY const char * -#define VAL_TY ProgramMetadataEntry -#include "kitty-verstable.h" - -static program_metadata_map program_layouts[arraysz(programs)]; -static bool program_layouts_initialized[arraysz(programs)] = {0}; - -static void -clear_program_layout(int program) { - if (!program_layouts_initialized[program]) return; - program_metadata_map *m = program_layouts + program; - vt_create_for_loop(program_metadata_map_itr, itr, m) free((void *)itr.data->key); - vt_cleanup(m); - program_layouts_initialized[program] = false; -} - -void -free_program_layouts(void) { - for (size_t i = 0; i < arraysz(program_layouts); i++) clear_program_layout((int)i); -} - -static void -insert_program_metadata(int program, const char *name, ProgramMetadataEntry entry) { - program_metadata_map_itr itr = vt_insert(program_layouts + program, strdup(name), entry); - if (vt_is_end(itr)) fatal("Out of memory adding program metadata entry: %s", name); -} - -static ProgramMetadataEntry * -program_metadata_entry(int program, const char *name, ProgramMetadataKind expected) { - program_metadata_map_itr itr = vt_get(program_layouts + program, name); - if (vt_is_end(itr)) fatal("No metadata entry named: %s for program: %d", name, program); - if (itr.data->val.kind != expected) fatal("The metadata entry named: %s for program: %d is not of the expected kind", name, program); - return &itr.data->val; -} - -void -set_program_layout(int program, PyObject *metadata) { - clear_program_layout(program); - vt_init(program_layouts + program); - program_layouts_initialized[program] = true; - - PyObject *key, *val; - Py_ssize_t pos; - - PyObject *loose_uniforms = PyDict_GetItemString(metadata, "loose_uniforms"); - pos = 0; - while (PyDict_Next(loose_uniforms, &pos, &key, &val)) { - const char *actual_name = PyUnicode_AsUTF8(val); - // The metadata records array uniforms with a [0] subscript to mark them - // as arrays, but init_uniforms() stores them under their bare name. - char without_subscript[256]; - const char *bracket = strchr(actual_name, '['); - if (bracket) { - size_t n = MIN(sizeof(without_subscript) - 1, (size_t)(bracket - actual_name)); - memcpy(without_subscript, actual_name, n); - without_subscript[n] = 0; - actual_name = without_subscript; - } - ProgramMetadataEntry e = {.kind = PROGRAM_UNIFORM, .location = get_uniform_location(program, actual_name)}; - insert_program_metadata(program, PyUnicode_AsUTF8(key), e); - } - - PyObject *input_locations = PyDict_GetItemString(metadata, "input_locations"); - pos = 0; - while (PyDict_Next(input_locations, &pos, &key, &val)) { - ProgramMetadataEntry e = {.kind = PROGRAM_ATTRIBUTE, .location = (GLint)PyLong_AsLong(val)}; - insert_program_metadata(program, PyUnicode_AsUTF8(key), e); - } - - PyObject *uniform_structs = PyDict_GetItemString(metadata, "uniform_structs"); - PyObject *uniform_struct_names = PyDict_GetItemString(metadata, "uniform_struct_names"); - pos = 0; - while (PyDict_Next(uniform_structs, &pos, &key, &val)) { - const char *glsl_block_name = PyUnicode_AsUTF8(PyDict_GetItem(uniform_struct_names, key)); - GLuint index = block_index(program, glsl_block_name); - ProgramMetadataEntry be = {.kind = PROGRAM_BLOCK, .block = {.size = block_size(program, index), .index = (GLint)index}}; - insert_program_metadata(program, PyUnicode_AsUTF8(key), be); - - PyObject *mkey, *mval; - Py_ssize_t mpos = 0; - while (PyDict_Next(val, &mpos, &mkey, &mval)) { - const char *decl = PyUnicode_AsUTF8(mval); - const char *bracket = strchr(decl, '['); - if (!bracket) continue; // scalar block members are hand-mirrored in C structs, not queried here - char actual_name[256]; - size_t n = MIN(sizeof(actual_name) - 1, (size_t)(bracket - decl)); - memcpy(actual_name, decl, n); - actual_name[n] = 0; - ProgramMetadataEntry ae = {.kind = PROGRAM_ARRAY, .array = get_uniform_array_information(program, actual_name)}; - insert_program_metadata(program, PyUnicode_AsUTF8(mkey), ae); - } - } -} - -GLint -program_uniform_location(int program, const char *name) { - ProgramMetadataEntry *e = program_metadata_entry(program, name, PROGRAM_UNIFORM); - // glUniform*() on location -1 is a silent no-op, so a uniform the driver - // does not report as active leaves whatever value it was last set to, - // rendering incorrectly with no other indication that anything is wrong. - if (e->location < 0 && !e->missing_location_logged) { - e->missing_location_logged = true; - log_error("The uniform: %s is not active in the linked GPU program: %d. Setting it will have no effect and rendering may be incorrect.", name, program); - } - return e->location; -} - -GLint -try_program_uniform_location(int program, const char *name) { - program_metadata_map_itr itr = vt_get(program_layouts + program, name); - if (vt_is_end(itr) || itr.data->val.kind != PROGRAM_UNIFORM) return -1; - return itr.data->val.location; -} - -GLint -program_attribute_location(int program, const char *name) { - return program_metadata_entry(program, name, PROGRAM_ATTRIBUTE)->location; -} - -UniformBlock -program_uniform_block(int program, const char *name) { - return program_metadata_entry(program, name, PROGRAM_BLOCK)->block; -} - -ArrayInformation -program_uniform_array(int program, const char *name) { - return program_metadata_entry(program, name, PROGRAM_ARRAY)->array; -} -// }}} - -void -bind_program(int program) { - glUseProgram(programs[program].id); -} - -void -unbind_program(void) { - glUseProgram(0); -} -// }}} - -// Buffers {{{ - -typedef struct { - GLuint id; - GLsizeiptr size; - GLenum usage; -} Buffer; - - -static Buffer buffers[MAX_CHILDREN * 6 + 4] = {{0}}; - -static ssize_t -create_buffer(GLenum usage) { - GLuint buffer_id; - glGenBuffers(1, &buffer_id); - for (size_t i = 0; i < sizeof(buffers) / sizeof(buffers[0]); i++) { - if (buffers[i].id == 0) { - buffers[i].id = buffer_id; - buffers[i].size = 0; - buffers[i].usage = usage; - return i; - } - } - glDeleteBuffers(1, &buffer_id); - fatal("Too many buffers"); - return -1; -} - -static void -delete_buffer(ssize_t buf_idx) { - glDeleteBuffers(1, &(buffers[buf_idx].id)); - buffers[buf_idx].id = 0; - buffers[buf_idx].size = 0; -} - -static GLuint -bind_buffer(ssize_t buf_idx) { - glBindBuffer(buffers[buf_idx].usage, buffers[buf_idx].id); - return buffers[buf_idx].id; -} - -static void -unbind_buffer(ssize_t buf_idx) { - glBindBuffer(buffers[buf_idx].usage, 0); -} - -static void -alloc_buffer(ssize_t idx, GLsizeiptr size, GLenum usage) { - Buffer *b = buffers + idx; - if (b->size == size) return; - b->size = size; - glBufferData(b->usage, size, NULL, usage); -} - -static void * -map_buffer(ssize_t idx, GLenum access) { - void *ans = glMapBuffer(buffers[idx].usage, access); - return ans; -} - -static void * -map_buffer_range(ssize_t idx, GLbitfield access, int offset, unsigned size) { - return glMapBufferRange(buffers[idx].usage, offset, size, access); -} - - -static void -unmap_buffer(ssize_t idx) { - glUnmapBuffer(buffers[idx].usage); -} - -// }}} - -// Vertex Array Objects (VAO) {{{ - -typedef struct { - GLuint id; - size_t num_buffers; - ssize_t buffers[10]; -} VAO; - -static VAO vaos[4 * MAX_CHILDREN + 10] = {{0}}; - -ssize_t -create_vao(void) { - GLuint vao_id; - glGenVertexArrays(1, &vao_id); - for (size_t i = 0; i < sizeof(vaos) / sizeof(vaos[0]); i++) { - if (!vaos[i].id) { - vaos[i].id = vao_id; - vaos[i].num_buffers = 0; - glBindVertexArray(vao_id); - return i; - } - } - glDeleteVertexArrays(1, &vao_id); - fatal("Too many VAOs"); - return -1; -} - -size_t -add_buffer_to_vao(ssize_t vao_idx, GLenum usage) { - VAO *vao = vaos + vao_idx; - if (vao->num_buffers >= sizeof(vao->buffers) / sizeof(vao->buffers[0])) { fatal("Too many buffers in a single VAO"); } - ssize_t buf = create_buffer(usage); - vao->buffers[vao->num_buffers++] = buf; - return vao->num_buffers - 1; -} - -static void -add_located_attribute_to_vao(ssize_t vao_idx, GLint aloc, GLint size, GLenum data_type, GLsizei stride, void *offset, GLuint divisor) { - VAO *vao = vaos + vao_idx; - if (!vao->num_buffers) fatal("You must create a buffer for this attribute first"); - ssize_t buf = vao->buffers[vao->num_buffers - 1]; - bind_buffer(buf); - glEnableVertexAttribArray(aloc); - switch (data_type) { - case GL_BYTE: - case GL_UNSIGNED_BYTE: - case GL_SHORT: - case GL_UNSIGNED_SHORT: - case GL_INT: - case GL_UNSIGNED_INT: glVertexAttribIPointer(aloc, size, data_type, stride, offset); break; - default: glVertexAttribPointer(aloc, size, data_type, GL_FALSE, stride, offset); break; - } - if (divisor) { glVertexAttribDivisorARB(aloc, divisor); } - unbind_buffer(buf); -} - - -void -add_attribute_to_vao(ssize_t vao_idx, int location, GLint size, GLenum data_type, GLsizei stride, void *offset, GLuint divisor) { - add_located_attribute_to_vao(vao_idx, location, size, data_type, stride, offset, divisor); -} - -void -set_vao_attribute(ssize_t vao_idx, size_t buffer_idx, int location, GLint size, GLenum data_type, GLsizei stride, void *offset, GLuint divisor) { - // (Re)configure an attribute pointer that reads from a specific buffer of - // the VAO (unlike add_attribute_to_vao which always uses the last added - // buffer). The VAO must be bound before calling this. - VAO *vao = vaos + vao_idx; - ssize_t buf = vao->buffers[buffer_idx]; - bind_buffer(buf); - glEnableVertexAttribArray(location); - switch (data_type) { - case GL_BYTE: - case GL_UNSIGNED_BYTE: - case GL_SHORT: - case GL_UNSIGNED_SHORT: - case GL_INT: - case GL_UNSIGNED_INT: glVertexAttribIPointer(location, size, data_type, stride, offset); break; - default: glVertexAttribPointer(location, size, data_type, GL_FALSE, stride, offset); break; - } - glVertexAttribDivisorARB(location, divisor); - unbind_buffer(buf); -} - -void -remove_vao(ssize_t vao_idx) { - VAO *vao = vaos + vao_idx; - while (vao->num_buffers) { - vao->num_buffers--; - delete_buffer(vao->buffers[vao->num_buffers]); - } - glDeleteVertexArrays(1, &(vao->id)); - vaos[vao_idx].id = 0; -} - -void -bind_vertex_array(ssize_t vao_idx) { - glBindVertexArray(vaos[vao_idx].id); -} - -void -unbind_vertex_array(void) { - glBindVertexArray(0); -} - -ssize_t -alloc_vao_buffer(ssize_t vao_idx, GLsizeiptr size, size_t bufnum, GLenum usage) { - ssize_t buf_idx = vaos[vao_idx].buffers[bufnum]; - bind_buffer(buf_idx); - alloc_buffer(buf_idx, size, usage); - return buf_idx; -} - -void * -map_vao_buffer_for_write_only(ssize_t vao_idx, size_t bufnum, int offset, unsigned size) { - ssize_t buf_idx = vaos[vao_idx].buffers[bufnum]; - bind_buffer(buf_idx); - return map_buffer_range(buf_idx, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT, offset, size); -} - -void * -alloc_and_map_vao_buffer(ssize_t vao_idx, GLsizeiptr size, size_t bufnum) { - ssize_t buf_idx = alloc_vao_buffer(vao_idx, size, bufnum, GL_STATIC_DRAW); - return map_buffer(buf_idx, GL_WRITE_ONLY); -} - -void * -alloc_and_map_vao_buffer_for_full_rewrite(ssize_t vao_idx, GLsizeiptr size, size_t bufnum) { - // The previous contents are discarded so the driver can hand out fresh - // storage instead of waiting for the GPU to finish reading the old data. - // The caller MUST write every byte of the mapped range, any byte not - // written is undefined. - ssize_t buf_idx = alloc_vao_buffer(vao_idx, size, bufnum, GL_STREAM_DRAW); - return map_buffer_range(buf_idx, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT, 0, (unsigned)size); -} - -void -bind_vao_uniform_buffer(ssize_t vao_idx, size_t bufnum, GLuint block_index) { - ssize_t buf_idx = vaos[vao_idx].buffers[bufnum]; - glBindBufferBase(GL_UNIFORM_BUFFER, block_index, buffers[buf_idx].id); -} - -void -unmap_vao_buffer(ssize_t vao_idx, size_t bufnum) { - ssize_t buf_idx = vaos[vao_idx].buffers[bufnum]; - unmap_buffer(buf_idx); - unbind_buffer(buf_idx); -} - -void -copy_vao_buffer_region(ssize_t vao_idx, size_t src_bufnum, GLintptr src_off, size_t dst_bufnum, GLintptr dst_off, GLsizeiptr size) { - ssize_t src_buf = vaos[vao_idx].buffers[src_bufnum]; - ssize_t dst_buf = vaos[vao_idx].buffers[dst_bufnum]; - glBindBuffer(GL_COPY_READ_BUFFER, buffers[src_buf].id); - glBindBuffer(GL_COPY_WRITE_BUFFER, buffers[dst_buf].id); - glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, src_off, dst_off, size); - glBindBuffer(GL_COPY_READ_BUFFER, 0); - glBindBuffer(GL_COPY_WRITE_BUFFER, 0); -} - -const void * -map_vao_buffer_for_reading(ssize_t vao_idx, size_t bufnum) { - ssize_t buf_idx = vaos[vao_idx].buffers[bufnum]; - bind_buffer(buf_idx); - return map_buffer(buf_idx, GL_READ_ONLY); -} - -// }}} diff --git a/kitty/gl.h b/kitty/gl.h deleted file mode 100644 index b317275b1..000000000 --- a/kitty/gl.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (C) 2017 Kovid Goyal - * - * Distributed under terms of the GPL3 license. - */ - -#pragma once - -#include "data-types.h" -#include "gl-wrapper.h" - -typedef struct { - GLint size, index; -} UniformBlock; - -typedef struct { - GLint offset; // byte offset from start of UBO - GLint stride; // element stride in bytes - GLint size; // umber of elements -} ArrayInformation; - -typedef struct { - char name[256]; - GLint size, location, idx; - GLenum type; -} Uniform; - -typedef struct { - GLuint id; - Uniform uniforms[256]; - GLint num_of_uniforms; -} Program; - -typedef struct Viewport { - unsigned left, top, width, height; -} Viewport; - -typedef enum { PROGRAM_UNIFORM, PROGRAM_ATTRIBUTE, PROGRAM_BLOCK, PROGRAM_ARRAY } ProgramMetadataKind; -typedef struct ProgramMetadataEntry { - ProgramMetadataKind kind; - bool missing_location_logged; - union { - GLint location; - UniformBlock block; - ArrayInformation array; - }; -} ProgramMetadataEntry; - -void gl_init(void); -const char *gl_version_string(void); -void set_gpu_viewport(unsigned w, unsigned h); -Viewport get_gpu_viewport(void); -void draw_quad(bool blend, unsigned instance_count); -void save_texture_as_png(uint32_t texture_id, const char *filename); -void free_texture(GLuint *tex_id); -void free_framebuffer(GLuint *fb_id); -void remove_vao(ssize_t vao_idx); -void init_uniforms(int program); -GLuint program_id(int program); -Program *program_ptr(int program); -GLuint block_index(int program, const char *name); -GLint block_size(int program, GLuint block_index); -GLint get_uniform_location(int program, const char *name); -GLint get_uniform_information(int program, const char *name, GLenum information_type); -ArrayInformation get_uniform_array_information(int program, const char *name); -GLint attrib_location(int program, const char *name); -void set_program_layout(int program, PyObject *metadata); -void free_program_layouts(void); -GLint program_uniform_location(int program, const char *name); -GLint try_program_uniform_location(int program, const char *name); -GLint program_attribute_location(int program, const char *name); -UniformBlock program_uniform_block(int program, const char *name); -ArrayInformation program_uniform_array(int program, const char *name); -ssize_t create_vao(void); -size_t add_buffer_to_vao(ssize_t vao_idx, GLenum usage); -void add_attribute_to_vao(ssize_t vao_idx, int location, GLint size, GLenum data_type, GLsizei stride, void *offset, GLuint divisor); -void set_vao_attribute(ssize_t vao_idx, size_t buffer_idx, int location, GLint size, GLenum data_type, GLsizei stride, void *offset, GLuint divisor); -ssize_t alloc_vao_buffer(ssize_t vao_idx, GLsizeiptr size, size_t bufnum, GLenum usage); -void *alloc_and_map_vao_buffer(ssize_t vao_idx, GLsizeiptr size, size_t bufnum); -// Discards the old contents, the caller must write every byte of the buffer -void *alloc_and_map_vao_buffer_for_full_rewrite(ssize_t vao_idx, GLsizeiptr size, size_t bufnum); -void unmap_vao_buffer(ssize_t vao_idx, size_t bufnum); -void *map_vao_buffer(ssize_t vao_idx, size_t bufnum, GLenum access); -void *map_vao_buffer_for_write_only(ssize_t vao_idx, size_t bufnum, int offset, unsigned size); -void bind_program(int program); -void bind_vertex_array(ssize_t vao_idx); -void bind_vao_uniform_buffer(ssize_t vao_idx, size_t bufnum, GLuint block_index); -void copy_vao_buffer_region(ssize_t vao_idx, size_t src_bufnum, GLintptr src_off, size_t dst_bufnum, GLintptr dst_off, GLsizeiptr size); -const void *map_vao_buffer_for_reading(ssize_t vao_idx, size_t bufnum); -void unbind_vertex_array(void); -void unbind_program(void); -GLuint compile_shaders(GLenum shader_type, GLsizei count, const GLchar *const *string); -void save_viewport_using_top_left_origin(GLsizei x, GLsizei y, GLsizei width, GLsizei height, GLsizei full_framebuffer_height); -void save_viewport_using_bottom_left_origin(GLsizei x, GLsizei y, GLsizei width, GLsizei height); -const char *check_framebuffer_status(void); -void restore_viewport(void); -void bind_framebuffer_for_output(unsigned fbid); -void set_framebuffer_to_use_for_output(unsigned fbid); -void enable_scissor_using_top_left_origin(Viewport, unsigned); -void disable_scissor(void); diff --git a/kitty/glfw.c b/kitty/glfw.c index c2661da51..71e42cefb 100644 --- a/kitty/glfw.c +++ b/kitty/glfw.c @@ -5,6 +5,7 @@ */ #include "state.h" +#include "gpu.h" #include "cleanup.h" #include "monotonic.h" #include "dnd.h" @@ -2782,10 +2783,10 @@ dbus_monitor_session_state(PyObject *self UNUSED, PyObject *callback) { static PyObject * glfw_init(PyObject UNUSED *self, PyObject *args) { - const char *path; + const char *path, *gpu_driver_path; int debug_keyboard = 0, debug_rendering = 0, wayland_enable_ime = 0; PyObject *edge_sf; - if (!PyArg_ParseTuple(args, "sO|ppp", &path, &edge_sf, &debug_keyboard, &debug_rendering, &wayland_enable_ime)) return NULL; + if (!PyArg_ParseTuple(args, "ssO|ppp", &path, &gpu_driver_path, &edge_sf, &debug_keyboard, &debug_rendering, &wayland_enable_ime)) return NULL; if (!PyCallable_Check(edge_sf)) { PyErr_SetString(PyExc_TypeError, "edge_spacing_func must be a callable"); return NULL; @@ -2800,6 +2801,11 @@ glfw_init(PyObject UNUSED *self, PyObject *args) { return NULL; } glfw_is_loaded = true; + err = load_gpu_driver(gpu_driver_path, debug_rendering != 0, glfwGetProcAddress); + if (err) { + PyErr_SetString(PyExc_RuntimeError, err); + return NULL; + } push_modifier_remap_to_glfw(); glfwSetErrorCallback(error_callback); glfwInitHint(GLFW_DEBUG_KEYBOARD, debug_keyboard); diff --git a/kitty/gpu.c b/kitty/gpu.c new file mode 100644 index 000000000..6d8418522 --- /dev/null +++ b/kitty/gpu.c @@ -0,0 +1,531 @@ +/* + * gpu.c + * Copyright (C) 2026 Kovid Goyal + * + * Distributed under terms of the GPL3 license. + */ + +#include "gpu.h" +#include "state.h" +#include "png-reader.h" +#include +#include +#include + +GPUDriver gpu_driver = {0}; + +// Driver loading {{{ +static void +driver_log_error(const char *msg) { + log_error("%s", msg); +} + +static void +driver_debug_print(const char *msg) { + timed_debug_print("%s\n", msg); +} + +static void +driver_fatal(const char *msg) { + fatal("%s", msg); +} + +const char * +load_gpu_driver(const char *path, bool debug_rendering, gpu_get_proc_address_func get_proc_address) { + static char errbuf[2048]; + if (gpu_driver.driver) return NULL; + void *handle = dlopen(path, RTLD_LAZY | RTLD_LOCAL); + if (!handle) { + snprintf(errbuf, sizeof(errbuf), "Failed to load the GPU driver from %s with error: %s", path, dlerror()); + return errbuf; + } + dlerror(); + gpu_driver_load_func load = NULL; + *(void **)(&load) = dlsym(handle, KITTY_GPU_DRIVER_ENTRY_POINT); + if (!load) { + snprintf(errbuf, sizeof(errbuf), "The GPU driver at %s does not export %s, with error: %s", path, KITTY_GPU_DRIVER_ENTRY_POINT, dlerror()); + dlclose(handle); + 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, + }; + GPUDriverAPI api = {0}; + void *driver = NULL; + char lerr[1024] = {0}; + if (!load(KITTY_GPU_API_VERSION, ¶ms, &api, &driver, lerr, sizeof(lerr))) { + snprintf(errbuf, sizeof(errbuf), "Failed to load the GPU driver from %s with error: %s", path, lerr); + dlclose(handle); + return errbuf; + } + if (api.api_version != KITTY_GPU_API_VERSION) { + snprintf(errbuf, sizeof(errbuf), "The GPU driver at %s implements API version %u instead of %u", path, api.api_version, KITTY_GPU_API_VERSION); + if (api.destroy) api.destroy(driver); + dlclose(handle); + return errbuf; + } + gpu_driver.api = api; + gpu_driver.driver = driver; + gpu_driver.dl_handle = handle; + gpu_driver.initialized = false; + return NULL; +} + +void +initialize_gpu_driver(void) { + if (gpu_driver.initialized) return; + if (!gpu_driver.driver) fatal("Cannot initialize the GPU as no GPU driver has been loaded"); + if (!gpu_driver.api.initialize(gpu_driver.driver)) + fatal("Failed to initialize the GPU driver with error: %s", gpu_driver.api.last_error(gpu_driver.driver)); + gpu_driver.initialized = true; +} + +void +unload_gpu_driver(void) { + // The shared library is not unloaded since code registered with + // atexit() or TLS destructors could still reference it + if (gpu_driver.driver) gpu_driver.api.destroy(gpu_driver.driver); + gpu_driver.driver = NULL; + gpu_driver.initialized = false; +} +// }}} + +// Viewports, framebuffers and textures {{{ +void +set_gpu_viewport(unsigned w, unsigned h) { + gpu_set_viewport(0, 0, w, h); +} + +static struct { + int32_t items[16][4]; + size_t used; +} saved_viewports; + +void +save_viewport_using_bottom_left_origin(int32_t newx, int32_t newy, uint32_t width, uint32_t height) { + if (saved_viewports.used >= arraysz(saved_viewports.items)) fatal("Too many nested saved viewports"); + int32_t *saved_viewport = saved_viewports.items[saved_viewports.used++]; + gpu_get_viewport(saved_viewport); + gpu_set_viewport(newx, newy, width, height); +} + +void +save_viewport_using_top_left_origin(int32_t newx, int32_t newy, uint32_t width, uint32_t height, int32_t full_framebuffer_height) { + // Converts the viewport defined by the specified arguments which are + // assumed to be in the usual co-ord system with origin at top left to the + // GPU viewport co-ord system with origin at bottom left. + // Use restore_viewport() to restore the viewport to what it was before. + newy = full_framebuffer_height - (newy + (int32_t)height); + save_viewport_using_bottom_left_origin(newx, newy, width, height); +} + +void +restore_viewport(void) { + if (!saved_viewports.used) fatal("Trying to restore a viewport when none is saved"); + const int32_t *saved_viewport = saved_viewports.items[--saved_viewports.used]; + gpu_set_viewport(saved_viewport[0], saved_viewport[1], (uint32_t)saved_viewport[2], (uint32_t)saved_viewport[3]); +} + +void +enable_scissor_using_top_left_origin(Viewport vp, unsigned full_framebuffer_height) { + int32_t newy = (int32_t)full_framebuffer_height - (int32_t)(vp.top + vp.height); + gpu_set_scissor(true, vp.left, newy, vp.width, vp.height); +} + +void +disable_scissor(void) { + gpu_set_scissor(false, 0, 0, 0, 0); +} + +void +draw_quad(bool blend, unsigned instance_count) { + gpu_draw_quad(instance_count, blend ? GPU_BLEND_PREMULTIPLIED_ALPHA : GPU_BLEND_NONE); +} + +// Resources can be freed by Python object destructors during interpreter +// shutdown, after the driver has been unloaded, in which case they are simply +// dropped, as the process is exiting. +void +free_texture(gpu_texture_t *tex) { + if (gpu_driver.driver) gpu_texture_destroy(*tex); + *tex = GPU_NULL_HANDLE; +} + +void +free_framebuffer(gpu_render_target_t *fb) { + if (gpu_driver.driver) gpu_render_target_destroy(*fb); + *fb = GPU_NULL_HANDLE; +} + +static gpu_render_target_t output_framebuffer = GPU_NULL_HANDLE; + +void +bind_framebuffer_for_output(gpu_render_target_t fb) { + gpu_set_render_target(fb ? fb : output_framebuffer); +} + +void +set_framebuffer_to_use_for_output(gpu_render_target_t fb) { + output_framebuffer = fb; +} + +const char * +check_framebuffer_status(void) { + return gpu_render_target_status(gpu_get_render_target()); +} + +static float +linear_to_srgb(float c) { + return (c <= 0.0031308f) ? 12.92f * c : 1.055f * powf(c, 1.0f / 2.4f) - 0.055f; +} + +void +save_texture_as_png(gpu_texture_t texture, const char *filename) { + GPUTextureDesc desc; + gpu_texture_get_desc(texture, &desc); + const size_t width = desc.width, height = desc.height; + size_t sz = sizeof(uint32_t) * width * height; + RAII_ALLOC(uint32_t, data, malloc(sz)); + if (!data) fatal("Out of memory"); + if (!gpu_texture_read(texture, GPU_PIXELS_RGBA8, data, sz)) fatal("Failed to read texture with error: %s", gpu_last_error()); + // assume data is linear and pre-multiplied + for (size_t i = 0; i < width * height; i++) { + uint32_t px = data[i]; + uint8_t r = (px >> 0) & 0xFF; + uint8_t g = (px >> 8) & 0xFF; + uint8_t b = (px >> 16) & 0xFF; + uint8_t a = (px >> 24) & 0xFF; + float alpha = a / 255.0f; + float rf = 0, gf = 0, bf = 0; + if (alpha > 0.0f) { + rf = (r / 255.0f) / alpha; + gf = (g / 255.0f) / alpha; + bf = (b / 255.0f) / alpha; + } + r = (uint8_t)(linear_to_srgb(rf) * 255); + g = (uint8_t)(linear_to_srgb(gf) * 255); + b = (uint8_t)(linear_to_srgb(bf) * 255); + data[i] = (r << 0) | (g << 8) | (b << 16) | ((uint32_t)a << 24); + } + const char *png = png_from_32bit_rgba((char *)data, width, height, &sz, true); + if (!sz) fatal("Failed to save PNG to %s with error: %s", filename, png); + FILE *file = fopen(filename, "wb"); + if (!file) fatal("Failed to open %s for writing with error: %s", filename, strerror(errno)); + fwrite(png, 1, sz, file); + fclose(file); +} +// }}} + +// Programs {{{ +typedef enum { PROGRAM_UNIFORM, PROGRAM_ATTRIBUTE, PROGRAM_BLOCK, PROGRAM_ARRAY } ProgramMetadataKind; +typedef struct ProgramMetadataEntry { + ProgramMetadataKind kind; + bool missing_location_logged; + union { + int32_t location; + UniformBlock block; + ArrayInformation array; + }; +} ProgramMetadataEntry; + +static gpu_pipeline_t programs[MAX_GPU_PROGRAMS] = {0}; + +gpu_pipeline_t +program_pipeline(int program) { + return programs[program]; +} + +void +set_program_pipeline(int program, gpu_pipeline_t pipeline) { + if (programs[program]) gpu_pipeline_destroy(programs[program]); + programs[program] = pipeline; +} + +int32_t +attrib_location(int program, const char *name) { + return gpu_pipeline_attribute_location(programs[program], name); +} + +static UniformBlock +block_info(int program, const char *name) { + GPUUniformBlockInfo info; + if (!gpu_pipeline_uniform_block(programs[program], name, &info)) fatal("%s", gpu_last_error()); + return (UniformBlock){.index = (int32_t)info.index, .size = (int32_t)info.size}; +} + +static ArrayInformation +get_uniform_array_information(int program, const char *name) { + GPUUniformArrayInfo info; + if (!gpu_pipeline_uniform_array(programs[program], name, &info)) fatal("%s", gpu_last_error()); + return (ArrayInformation){.offset = (int32_t)info.offset, .stride = (int32_t)info.stride, .size = (int32_t)info.count}; +} + +// Program metadata (uniform/attribute locations and UBO/array info, looked up by name) {{{ +#define NAME program_metadata_map +#define KEY_TY const char * +#define VAL_TY ProgramMetadataEntry +#include "kitty-verstable.h" + +static program_metadata_map program_layouts[MAX_GPU_PROGRAMS]; +static bool program_layouts_initialized[MAX_GPU_PROGRAMS] = {0}; + +static void +clear_program_layout(int program) { + if (!program_layouts_initialized[program]) return; + program_metadata_map *m = program_layouts + program; + vt_create_for_loop(program_metadata_map_itr, itr, m) free((void *)itr.data->key); + vt_cleanup(m); + program_layouts_initialized[program] = false; +} + +void +free_program_layouts(void) { + for (size_t i = 0; i < arraysz(program_layouts); i++) clear_program_layout((int)i); +} + +static void +insert_program_metadata(int program, const char *name, ProgramMetadataEntry entry) { + program_metadata_map_itr itr = vt_insert(program_layouts + program, strdup(name), entry); + if (vt_is_end(itr)) fatal("Out of memory adding program metadata entry: %s", name); +} + +static ProgramMetadataEntry * +program_metadata_entry(int program, const char *name, ProgramMetadataKind expected) { + program_metadata_map_itr itr = vt_get(program_layouts + program, name); + if (vt_is_end(itr)) fatal("No metadata entry named: %s for program: %d", name, program); + if (itr.data->val.kind != expected) fatal("The metadata entry named: %s for program: %d is not of the expected kind", name, program); + return &itr.data->val; +} + +void +set_program_layout(int program, PyObject *metadata) { + clear_program_layout(program); + vt_init(program_layouts + program); + program_layouts_initialized[program] = true; + + PyObject *key, *val; + Py_ssize_t pos; + + PyObject *loose_uniforms = PyDict_GetItemString(metadata, "loose_uniforms"); + pos = 0; + while (PyDict_Next(loose_uniforms, &pos, &key, &val)) { + const char *actual_name = PyUnicode_AsUTF8(val); + // The metadata records array uniforms with a [0] subscript to mark them + // as arrays, but the driver looks them up by their bare name. + char without_subscript[256]; + const char *bracket = strchr(actual_name, '['); + if (bracket) { + size_t n = MIN(sizeof(without_subscript) - 1, (size_t)(bracket - actual_name)); + memcpy(without_subscript, actual_name, n); + without_subscript[n] = 0; + actual_name = without_subscript; + } + ProgramMetadataEntry e = {.kind = PROGRAM_UNIFORM, .location = gpu_pipeline_uniform_slot(programs[program], actual_name)}; + insert_program_metadata(program, PyUnicode_AsUTF8(key), e); + } + + PyObject *input_locations = PyDict_GetItemString(metadata, "input_locations"); + pos = 0; + while (PyDict_Next(input_locations, &pos, &key, &val)) { + ProgramMetadataEntry e = {.kind = PROGRAM_ATTRIBUTE, .location = (int32_t)PyLong_AsLong(val)}; + insert_program_metadata(program, PyUnicode_AsUTF8(key), e); + } + + PyObject *uniform_structs = PyDict_GetItemString(metadata, "uniform_structs"); + PyObject *uniform_struct_names = PyDict_GetItemString(metadata, "uniform_struct_names"); + pos = 0; + while (PyDict_Next(uniform_structs, &pos, &key, &val)) { + const char *glsl_block_name = PyUnicode_AsUTF8(PyDict_GetItem(uniform_struct_names, key)); + ProgramMetadataEntry be = {.kind = PROGRAM_BLOCK, .block = block_info(program, glsl_block_name)}; + insert_program_metadata(program, PyUnicode_AsUTF8(key), be); + + PyObject *mkey, *mval; + Py_ssize_t mpos = 0; + while (PyDict_Next(val, &mpos, &mkey, &mval)) { + const char *decl = PyUnicode_AsUTF8(mval); + const char *bracket = strchr(decl, '['); + if (!bracket) continue; // scalar block members are hand-mirrored in C structs, not queried here + char actual_name[256]; + size_t n = MIN(sizeof(actual_name) - 1, (size_t)(bracket - decl)); + memcpy(actual_name, decl, n); + actual_name[n] = 0; + ProgramMetadataEntry ae = {.kind = PROGRAM_ARRAY, .array = get_uniform_array_information(program, actual_name)}; + insert_program_metadata(program, PyUnicode_AsUTF8(mkey), ae); + } + } +} + +int32_t +program_uniform_location(int program, const char *name) { + ProgramMetadataEntry *e = program_metadata_entry(program, name, PROGRAM_UNIFORM); + // Setting a uniform at location -1 is a silent no-op, so a uniform the driver + // does not report as active leaves whatever value it was last set to, + // rendering incorrectly with no other indication that anything is wrong. + if (e->location < 0 && !e->missing_location_logged) { + e->missing_location_logged = true; + log_error("The uniform: %s is not active in the linked GPU program: %d. Setting it will have no effect and rendering may be incorrect.", name, program); + } + return e->location; +} + +int32_t +try_program_uniform_location(int program, const char *name) { + program_metadata_map_itr itr = vt_get(program_layouts + program, name); + if (vt_is_end(itr) || itr.data->val.kind != PROGRAM_UNIFORM) return -1; + return itr.data->val.location; +} + +int32_t +program_attribute_location(int program, const char *name) { + return program_metadata_entry(program, name, PROGRAM_ATTRIBUTE)->location; +} + +UniformBlock +program_uniform_block(int program, const char *name) { + return program_metadata_entry(program, name, PROGRAM_BLOCK)->block; +} + +ArrayInformation +program_uniform_array(int program, const char *name) { + return program_metadata_entry(program, name, PROGRAM_ARRAY)->array; +} +// }}} + +void +bind_program_uniform_block(int program, const char *name, uint32_t binding_point) { + UniformBlock b = program_uniform_block(program, name); + gpu_pipeline_bind_uniform_block(programs[program], (uint32_t)b.index, binding_point); +} + +void +bind_program(int program) { + gpu_use_pipeline(programs[program]); +} + +void +unbind_program(void) { + gpu_use_pipeline(GPU_NULL_HANDLE); +} +// }}} + +// Vertex Array Objects (VAO) {{{ +typedef struct { + gpu_vertex_layout_t layout; + size_t num_buffers; + gpu_buffer_t buffers[10]; +} VAO; + +static VAO vaos[4 * MAX_CHILDREN + 10] = {{0}}; + +ssize_t +create_vao(void) { + for (size_t i = 0; i < arraysz(vaos); i++) { + if (!vaos[i].layout) { + gpu_vertex_layout_t layout = gpu_vertex_layout_create(); + if (!layout) fatal("Failed to create a vertex layout with error: %s", gpu_last_error()); + vaos[i].layout = layout; + vaos[i].num_buffers = 0; + gpu_bind_vertex_layout(layout); + return i; + } + } + fatal("Too many VAOs"); + return -1; +} + +size_t +add_buffer_to_vao(ssize_t vao_idx, GPUBufferKind kind) { + VAO *vao = vaos + vao_idx; + if (vao->num_buffers >= arraysz(vao->buffers)) fatal("Too many buffers in a single VAO"); + gpu_buffer_t buf = gpu_buffer_create(kind); + if (!buf) fatal("Failed to create a GPU buffer with error: %s", gpu_last_error()); + vao->buffers[vao->num_buffers++] = buf; + return vao->num_buffers - 1; +} + +void +add_attribute_to_vao(ssize_t vao_idx, int location, uint32_t components, GPUAttribType type, uint32_t stride, size_t offset, uint32_t divisor) { + VAO *vao = vaos + vao_idx; + if (!vao->num_buffers) fatal("You must create a buffer for this attribute first"); + set_vao_attribute(vao_idx, vao->num_buffers - 1, location, components, type, stride, offset, divisor); +} + +void +set_vao_attribute(ssize_t vao_idx, size_t buffer_idx, int location, uint32_t components, GPUAttribType type, uint32_t stride, size_t offset, uint32_t divisor) { + VAO *vao = vaos + vao_idx; + gpu_vertex_layout_set_attribute(vao->layout, (uint32_t)location, vao->buffers[buffer_idx], components, type, stride, offset, divisor); +} + +void +remove_vao(ssize_t vao_idx) { + VAO *vao = vaos + vao_idx; + const bool loaded = gpu_driver.driver != NULL; // see free_texture() + while (vao->num_buffers) { + vao->num_buffers--; + if (loaded) gpu_buffer_destroy(vao->buffers[vao->num_buffers]); + vao->buffers[vao->num_buffers] = GPU_NULL_HANDLE; + } + if (loaded) gpu_vertex_layout_destroy(vao->layout); + vao->layout = GPU_NULL_HANDLE; +} + +void +bind_vertex_array(ssize_t vao_idx) { + gpu_bind_vertex_layout(vaos[vao_idx].layout); +} + +void +unbind_vertex_array(void) { + gpu_bind_vertex_layout(GPU_NULL_HANDLE); +} + +void +alloc_vao_buffer(ssize_t vao_idx, size_t size, size_t bufnum, GPUUpdateFrequency frequency) { + gpu_buffer_allocate(vaos[vao_idx].buffers[bufnum], size, frequency); +} + +void * +map_vao_buffer_for_write_only(ssize_t vao_idx, size_t bufnum, size_t offset, size_t size) { + return gpu_buffer_map(vaos[vao_idx].buffers[bufnum], GPU_MAP_WRITE_DISCARD_RANGE, offset, size); +} + +void * +alloc_and_map_vao_buffer(ssize_t vao_idx, size_t size, size_t bufnum) { + alloc_vao_buffer(vao_idx, size, bufnum, GPU_UPDATE_RARELY); + return gpu_buffer_map(vaos[vao_idx].buffers[bufnum], GPU_MAP_WRITE, 0, size); +} + +void * +alloc_and_map_vao_buffer_for_full_rewrite(ssize_t vao_idx, size_t size, size_t bufnum) { + // The previous contents are discarded so the driver can hand out fresh + // storage instead of waiting for the GPU to finish reading the old data. + // The caller MUST write every byte of the mapped range, any byte not + // written is undefined. + alloc_vao_buffer(vao_idx, size, bufnum, GPU_UPDATE_EVERY_USE); + return gpu_buffer_map(vaos[vao_idx].buffers[bufnum], GPU_MAP_WRITE_DISCARD_ALL, 0, size); +} + +const void * +map_vao_buffer_for_reading(ssize_t vao_idx, size_t bufnum) { + return gpu_buffer_map(vaos[vao_idx].buffers[bufnum], GPU_MAP_READ, 0, 0); +} + +void +unmap_vao_buffer(ssize_t vao_idx, size_t bufnum) { + gpu_buffer_unmap(vaos[vao_idx].buffers[bufnum]); +} + +void +bind_vao_uniform_buffer(ssize_t vao_idx, size_t bufnum, uint32_t binding_point) { + gpu_bind_uniform_buffer(binding_point, vaos[vao_idx].buffers[bufnum]); +} + +void +copy_vao_buffer_region(ssize_t vao_idx, size_t src_bufnum, size_t src_off, size_t dst_bufnum, size_t dst_off, size_t size) { + gpu_buffer_copy(vaos[vao_idx].buffers[src_bufnum], src_off, vaos[vao_idx].buffers[dst_bufnum], dst_off, size); +} +// }}} diff --git a/kitty/gpu.h b/kitty/gpu.h new file mode 100644 index 000000000..dfe86f16a --- /dev/null +++ b/kitty/gpu.h @@ -0,0 +1,383 @@ +/* + * gpu.h + * Copyright (C) 2026 Kovid Goyal + * + * Distributed under terms of the GPL3 license. + */ + +// Loading of the GPU driver and thin, type safe wrappers around the driver +// API defined in gpu/api.h, plus the higher level helpers used by the rendering +// code in shaders.c. + +#pragma once + +#include "data-types.h" +#include "../gpu/api.h" + +typedef struct GPUDriver { + GPUDriverAPI api; + void *driver; + void *dl_handle; + bool initialized; +} 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 +void initialize_gpu_driver(void); +void unload_gpu_driver(void); + +// Driver API wrappers {{{ +#define D gpu_driver.driver +#define A gpu_driver.api + +static inline const char * +gpu_last_error(void) { + return A.last_error(D); +} + +static inline const char * +gpu_version_string(void) { + return gpu_driver.initialized ? A.version_string(D) : ""; +} + +static inline void +gpu_get_capabilities(GPUCapabilities *ans) { + A.get_capabilities(D, ans); +} + +static inline gpu_texture_t +gpu_texture_create(const GPUTextureDesc *desc, const GPUPixelData *initial) { + return A.texture_create(D, desc, initial); +} + +static inline bool +gpu_texture_reset(gpu_texture_t texture, const GPUTextureDesc *desc, const GPUPixelData *initial) { + return A.texture_reset(D, texture, desc, initial); +} + +static inline void +gpu_texture_destroy(gpu_texture_t texture) { + A.texture_destroy(D, texture); +} + +static inline void +gpu_texture_upload(gpu_texture_t texture, uint32_t x, uint32_t y, uint32_t layer, uint32_t width, uint32_t height, const GPUPixelData *pixels) { + A.texture_upload(D, texture, x, y, layer, width, height, pixels); +} + +static inline void +gpu_texture_copy(gpu_texture_t src, gpu_texture_t dst) { + A.texture_copy(D, src, dst); +} + +static inline bool +gpu_texture_read(gpu_texture_t texture, GPUPixelLayout layout, void *dst, size_t dst_size) { + return A.texture_read(D, texture, layout, dst, dst_size); +} + +static inline void +gpu_texture_get_desc(gpu_texture_t texture, GPUTextureDesc *ans) { + A.texture_get_desc(D, texture, ans); +} + +static inline void +gpu_bind_texture(uint32_t unit, gpu_texture_t texture) { + A.bind_texture(D, unit, texture); +} + +static inline gpu_buffer_t +gpu_buffer_create(GPUBufferKind kind) { + return A.buffer_create(D, kind); +} + +static inline void +gpu_buffer_destroy(gpu_buffer_t buffer) { + A.buffer_destroy(D, buffer); +} + +static inline void +gpu_buffer_allocate(gpu_buffer_t buffer, size_t size, GPUUpdateFrequency frequency) { + A.buffer_allocate(D, buffer, size, frequency); +} + +static inline void * +gpu_buffer_map(gpu_buffer_t buffer, GPUMapMode mode, size_t offset, size_t size) { + return A.buffer_map(D, buffer, mode, offset, size); +} + +static inline void +gpu_buffer_unmap(gpu_buffer_t buffer) { + A.buffer_unmap(D, buffer); +} + +static inline void +gpu_buffer_copy(gpu_buffer_t src, size_t src_offset, gpu_buffer_t dst, size_t dst_offset, size_t size) { + A.buffer_copy(D, src, src_offset, dst, dst_offset, size); +} + +static inline void +gpu_bind_uniform_buffer(uint32_t binding_point, gpu_buffer_t buffer) { + A.bind_uniform_buffer(D, binding_point, buffer); +} + +static inline gpu_pipeline_t +gpu_pipeline_create(const GPUShaderSource *sources, size_t num_sources) { + return A.pipeline_create(D, sources, num_sources); +} + +static inline void +gpu_pipeline_destroy(gpu_pipeline_t pipeline) { + A.pipeline_destroy(D, pipeline); +} + +static inline void +gpu_use_pipeline(gpu_pipeline_t pipeline) { + A.use_pipeline(D, pipeline); +} + +static inline int32_t +gpu_pipeline_uniform_slot(gpu_pipeline_t pipeline, const char *name) { + return A.pipeline_uniform_slot(D, pipeline, name); +} + +static inline bool +gpu_pipeline_uniform_block(gpu_pipeline_t pipeline, const char *name, GPUUniformBlockInfo *ans) { + return A.pipeline_uniform_block(D, pipeline, name, ans); +} + +static inline bool +gpu_pipeline_uniform_array(gpu_pipeline_t pipeline, const char *name, GPUUniformArrayInfo *ans) { + return A.pipeline_uniform_array(D, pipeline, name, ans); +} + +static inline void +gpu_pipeline_bind_uniform_block(gpu_pipeline_t pipeline, uint32_t block_index, uint32_t binding_point) { + A.pipeline_bind_uniform_block(D, pipeline, block_index, binding_point); +} + +static inline int32_t +gpu_pipeline_attribute_location(gpu_pipeline_t pipeline, const char *name) { + return A.pipeline_attribute_location(D, pipeline, name); +} + +static inline void +gpu_set_uniform_floats(int32_t slot, uint32_t components, uint32_t count, const float *values) { + A.set_uniform_floats(D, slot, components, count, values); +} + +static inline void +gpu_set_uniform_ints(int32_t slot, uint32_t components, uint32_t count, const int32_t *values) { + A.set_uniform_ints(D, slot, components, count, values); +} + +static inline void +gpu_set_uniform_uints(int32_t slot, uint32_t components, uint32_t count, const uint32_t *values) { + A.set_uniform_uints(D, slot, components, count, values); +} + +static inline gpu_vertex_layout_t +gpu_vertex_layout_create(void) { + return A.vertex_layout_create(D); +} + +static inline void +gpu_vertex_layout_destroy(gpu_vertex_layout_t layout) { + A.vertex_layout_destroy(D, layout); +} + +static inline void +gpu_bind_vertex_layout(gpu_vertex_layout_t layout) { + A.bind_vertex_layout(D, layout); +} + +static inline void +gpu_vertex_layout_set_attribute( + gpu_vertex_layout_t layout, + uint32_t location, + gpu_buffer_t buffer, + uint32_t components, + GPUAttribType type, + uint32_t stride, + size_t offset, + uint32_t instance_divisor) { + A.vertex_layout_set_attribute(D, layout, location, buffer, components, type, stride, offset, instance_divisor); +} + +static inline gpu_render_target_t +gpu_render_target_create(gpu_texture_t color_texture) { + return A.render_target_create(D, color_texture); +} + +static inline void +gpu_render_target_destroy(gpu_render_target_t target) { + A.render_target_destroy(D, target); +} + +static inline void +gpu_set_render_target(gpu_render_target_t target) { + A.set_render_target(D, target); +} + +static inline gpu_render_target_t +gpu_get_render_target(void) { + return A.get_render_target(D); +} + +static inline const char * +gpu_render_target_status(gpu_render_target_t target) { + return A.render_target_status(D, target); +} + +static inline void +gpu_clear(float r, float g, float b, float a) { + A.clear(D, r, g, b, a); +} + +static inline void +gpu_set_viewport(int32_t x, int32_t y, uint32_t width, uint32_t height) { + A.set_viewport(D, x, y, width, height); +} + +static inline void +gpu_get_viewport(int32_t ans[4]) { + A.get_viewport(D, ans); +} + +static inline void +gpu_set_scissor(bool enabled, int32_t x, int32_t y, uint32_t width, uint32_t height) { + A.set_scissor(D, enabled, x, y, width, height); +} + +static inline void +gpu_set_srgb_output(bool enabled) { + A.set_srgb_output(D, enabled); +} + +static inline void +gpu_read_pixels(int32_t x, int32_t y, uint32_t width, uint32_t height, void *dst) { + A.read_pixels(D, x, y, width, height, dst); +} + +static inline void +gpu_copy_to_texture(gpu_texture_t dst, int32_t x, int32_t y, uint32_t width, uint32_t height) { + A.copy_to_texture(D, dst, x, y, width, height); +} + +static inline void +gpu_draw_quad(uint32_t instance_count, GPUBlendMode blend) { + A.draw_quad(D, instance_count, blend); +} +#undef D +#undef A +// }}} + +// Uniform convenience functions {{{ +static inline void +gpu_uniform1f(int32_t slot, float a) { + gpu_set_uniform_floats(slot, 1, 1, &a); +} + +static inline void +gpu_uniform2f(int32_t slot, float a, float b) { + const float v[2] = {a, b}; + gpu_set_uniform_floats(slot, 2, 1, v); +} + +static inline void +gpu_uniform3f(int32_t slot, float a, float b, float c) { + const float v[3] = {a, b, c}; + gpu_set_uniform_floats(slot, 3, 1, v); +} + +static inline void +gpu_uniform4f(int32_t slot, float a, float b, float c, float d) { + const float v[4] = {a, b, c, d}; + gpu_set_uniform_floats(slot, 4, 1, v); +} + +static inline void +gpu_uniform1i(int32_t slot, int32_t a) { + gpu_set_uniform_ints(slot, 1, 1, &a); +} + +static inline void +gpu_uniform1ui(int32_t slot, uint32_t a) { + gpu_set_uniform_uints(slot, 1, 1, &a); +} +// }}} + +// Higher level helpers {{{ +typedef struct Viewport { + unsigned left, top, width, height; +} Viewport; + +void set_gpu_viewport(unsigned w, unsigned h); +void save_viewport_using_top_left_origin(int32_t x, int32_t y, uint32_t width, uint32_t height, int32_t full_framebuffer_height); +void save_viewport_using_bottom_left_origin(int32_t x, int32_t y, uint32_t width, uint32_t height); +void restore_viewport(void); +void enable_scissor_using_top_left_origin(Viewport, unsigned); +void disable_scissor(void); +// Draw a quad, blending pre-multiplied colors if blend is true +void draw_quad(bool blend, unsigned instance_count); +void free_texture(gpu_texture_t *tex); +void free_framebuffer(gpu_render_target_t *fb); +// The render target used for output, render target zero is redirected to +// the target set with set_framebuffer_to_use_for_output() +void bind_framebuffer_for_output(gpu_render_target_t fb); +void set_framebuffer_to_use_for_output(gpu_render_target_t fb); +const char *check_framebuffer_status(void); +void save_texture_as_png(gpu_texture_t texture, const char *filename); +// }}} + +// Programs {{{ +typedef struct UniformBlock { + int32_t size, index; +} UniformBlock; + +typedef struct ArrayInformation { + int32_t offset; // byte offset from start of UBO + int32_t stride; // element stride in bytes + int32_t size; // number of elements +} ArrayInformation; + +#define MAX_GPU_PROGRAMS 64 + +gpu_pipeline_t program_pipeline(int program); +// Replace the pipeline of program, freeing any existing pipeline. Steals the reference to pipeline. +void set_program_pipeline(int program, gpu_pipeline_t pipeline); +int32_t attrib_location(int program, const char *name); +void set_program_layout(int program, PyObject *metadata); +void free_program_layouts(void); +int32_t program_uniform_location(int program, const char *name); +int32_t try_program_uniform_location(int program, const char *name); +int32_t program_attribute_location(int program, const char *name); +UniformBlock program_uniform_block(int program, const char *name); +ArrayInformation program_uniform_array(int program, const char *name); +void bind_program_uniform_block(int program, const char *name, uint32_t binding_point); +void bind_program(int program); +void unbind_program(void); +// }}} + +// Vertex array objects: a vertex layout together with the buffers it uses {{{ +ssize_t create_vao(void); +size_t add_buffer_to_vao(ssize_t vao_idx, GPUBufferKind kind); +// Add an attribute reading from the most recently added buffer +void add_attribute_to_vao(ssize_t vao_idx, int location, uint32_t components, GPUAttribType type, uint32_t stride, size_t offset, uint32_t divisor); +void +set_vao_attribute(ssize_t vao_idx, size_t buffer_idx, int location, uint32_t components, GPUAttribType type, uint32_t stride, size_t offset, uint32_t divisor); +void remove_vao(ssize_t vao_idx); +void bind_vertex_array(ssize_t vao_idx); +void unbind_vertex_array(void); +void alloc_vao_buffer(ssize_t vao_idx, size_t size, size_t bufnum, GPUUpdateFrequency frequency); +void *alloc_and_map_vao_buffer(ssize_t vao_idx, size_t size, size_t bufnum); +// Discards the old contents, the caller must write every byte of the buffer +void *alloc_and_map_vao_buffer_for_full_rewrite(ssize_t vao_idx, size_t size, size_t bufnum); +void *map_vao_buffer_for_write_only(ssize_t vao_idx, size_t bufnum, size_t offset, size_t size); +const void *map_vao_buffer_for_reading(ssize_t vao_idx, size_t bufnum); +void unmap_vao_buffer(ssize_t vao_idx, size_t bufnum); +void bind_vao_uniform_buffer(ssize_t vao_idx, size_t bufnum, uint32_t binding_point); +void copy_vao_buffer_region(ssize_t vao_idx, size_t src_bufnum, size_t src_off, size_t dst_bufnum, size_t dst_off, size_t size); +// }}} diff --git a/kitty/graphics.c b/kitty/graphics.c index 7388c670a..467e08967 100644 --- a/kitty/graphics.c +++ b/kitty/graphics.c @@ -8,6 +8,7 @@ #define GRAPHICS_INTERNAL_APIS #include "graphics.h" #include "state.h" +#include "gpu.h" #include "disk-cache.h" #include "iqsort.h" #include "safe-wrappers.h" @@ -161,7 +162,7 @@ new_texture_ref(void) { return ans; } -static uint32_t +static gpu_texture_t texture_id_for_img(Image *img) { return img->texture ? img->texture->id : 0; } @@ -2972,12 +2973,12 @@ image_as_dict(GraphicsManager *self, Image *img) { return NULL; } PyObject *ans = Py_BuildValue( - "{sI sI sI sI sI sI sI " + "{sK sI sI sI sI sI sI " "sO sI sO " "sI sI sI " "sI sI sy# sN sI}", "texture_id", - texture_id_for_img(img), + (unsigned long long)texture_id_for_img(img), U(client_id), U(width), U(height), diff --git a/kitty/graphics.h b/kitty/graphics.h index 12872cfc1..29dede82d 100644 --- a/kitty/graphics.h +++ b/kitty/graphics.h @@ -50,7 +50,8 @@ typedef struct { typedef struct { ImageRect src_rect, dest_rect; - uint32_t texture_id, group_count; + gpu_texture_t texture_id; + uint32_t group_count; int z_index; // Zero for normal images, otherwise the number of bytes per pixel of an indexed color image uint8_t indexed_px_sz; @@ -61,7 +62,7 @@ typedef struct { } ImageRenderData; typedef struct { - uint32_t texture_id; + gpu_texture_t texture_id; unsigned int height, width; uint8_t *bitmap; uint32_t refcnt, id; @@ -103,7 +104,8 @@ typedef struct { typedef enum { ANIMATION_STOPPED = 0, ANIMATION_LOADING = 1, ANIMATION_RUNNING = 2 } AnimationState; typedef struct TextureRef { - uint32_t id, refcnt; + gpu_texture_t id; + uint32_t refcnt; } TextureRef; #define NAME ref_map diff --git a/kitty/main.py b/kitty/main.py index 3c705c663..b78362e33 100644 --- a/kitty/main.py +++ b/kitty/main.py @@ -23,6 +23,7 @@ from .constants import ( beam_cursor_data_file, clear_handled_signals, glfw_path, + gpu_driver_path, is_macos, is_quick_access_terminal_app, is_wayland, @@ -105,7 +106,7 @@ def load_all_shaders() -> None: def init_glfw_module(glfw_module: str = 'wayland', debug_keyboard: bool = False, debug_rendering: bool = False, wayland_enable_ime: bool = True) -> None: - ok, swo = glfw_init(glfw_path(glfw_module), edge_spacing, debug_keyboard, debug_rendering, wayland_enable_ime) + ok, swo = glfw_init(glfw_path(glfw_module), gpu_driver_path(), edge_spacing, debug_keyboard, debug_rendering, wayland_enable_ime) if not ok: raise SystemExit('GLFW initialization failed') supports_window_occlusion(swo) diff --git a/kitty/shaders.c b/kitty/shaders.c index 72c50ac26..e4eed8802 100644 --- a/kitty/shaders.c +++ b/kitty/shaders.c @@ -6,7 +6,7 @@ */ #include "fonts.h" -#include "gl.h" +#include "gpu.h" #include "cleanup.h" #include "colors.h" #include @@ -42,6 +42,7 @@ enum { NUM_PROGRAMS }; +static_assert(NUM_PROGRAMS <= MAX_GPU_PROGRAMS, "Too many GPU programs"); enum { SPRITE_MAP_UNIT, GRAPHICS_UNIT, SPRITE_DECORATIONS_MAP_UNIT, CUSTOM_END_TEXTURE_A_UNIT, CUSTOM_END_TEXTURE_B_UNIT, CUSTOM_END_TEXTURE_PERSIST_UNIT }; typedef struct UIRenderData { @@ -66,43 +67,43 @@ row_offset_for_screen(const Screen *screen) { // Sprites {{{ typedef struct { int xnum, ynum, x, y, z, last_num_of_layers, last_ynum; - GLuint texture_id; - GLint max_texture_size, max_array_texture_layers; + gpu_texture_t texture_id; + int32_t max_texture_size, max_array_texture_layers; struct decorations_map { - GLuint texture_id; + gpu_texture_t texture_id; unsigned width, height; size_t count; } decorations_map; } SpriteMap; static const SpriteMap NEW_SPRITE_MAP = {.xnum = 1, .ynum = 1, .last_num_of_layers = 1, .last_ynum = -1}; -static GLint max_texture_size = 0, max_array_texture_layers = 0; +static int32_t max_texture_size = 0, max_array_texture_layers = 0; -static GLfloat +static float srgb_color(uint8_t color) { return srgb_lut[color]; } static void -color_vec3(GLint location, color_type color) { - glUniform3f(location, srgb_lut[(color >> 16) & 0xFF], srgb_lut[(color >> 8) & 0xFF], srgb_lut[color & 0xFF]); +color_vec3(int32_t location, color_type color) { + gpu_uniform3f(location, srgb_lut[(color >> 16) & 0xFF], srgb_lut[(color >> 8) & 0xFF], srgb_lut[color & 0xFF]); } static void -color_vec4_premult(GLint location, color_type color, GLfloat alpha) { - glUniform4f(location, srgb_lut[(color >> 16) & 0xFF] * alpha, srgb_lut[(color >> 8) & 0xFF] * alpha, srgb_lut[color & 0xFF] * alpha, alpha); +color_vec4_premult(int32_t location, color_type color, float alpha) { + gpu_uniform4f(location, srgb_lut[(color >> 16) & 0xFF] * alpha, srgb_lut[(color >> 8) & 0xFF] * alpha, srgb_lut[color & 0xFF] * alpha, alpha); } static void -color_vec4(GLint location, color_type color, GLfloat alpha) { - glUniform4f(location, srgb_lut[(color >> 16) & 0xFF], srgb_lut[(color >> 8) & 0xFF], srgb_lut[color & 0xFF], alpha); +color_vec4(int32_t location, color_type color, float alpha) { + gpu_uniform4f(location, srgb_lut[(color >> 16) & 0xFF], srgb_lut[(color >> 8) & 0xFF], srgb_lut[color & 0xFF], alpha); } // Write a color into a std140 float4 whose fourth component is unused. Uses // the same table as the shaders so the result is identical to converting the // color in the shader. static void -linear_color_vec4(GLfloat *dest, color_type color) { +linear_color_vec4(float *dest, color_type color) { dest[0] = srgb_lut[(color >> 16) & 0xFF]; dest[1] = srgb_lut[(color >> 8) & 0xFF]; dest[2] = srgb_lut[color & 0xFF]; @@ -112,24 +113,19 @@ linear_color_vec4(GLfloat *dest, color_type color) { static void clear_current_framebuffer(void) { - glClearColor(0, 0, 0, 0); - glClear(GL_COLOR_BUFFER_BIT); + gpu_clear(0, 0, 0, 0); } -// Must be called as soon as there is a current OpenGL context, see +// Must be called as soon as there is an initialized GPU driver, see // initialize_gpu(). Font groups are created before that happens and size their // sprite layout using these limits, so the sooner they are known the better. static void query_gpu_texture_limits(void) { - if (max_texture_size) return; - glGetIntegerv(GL_MAX_TEXTURE_SIZE, &(max_texture_size)); - glGetIntegerv(GL_MAX_ARRAY_TEXTURE_LAYERS, &(max_array_texture_layers)); -#ifdef __APPLE__ - // Since on Apple we could have multiple GPUs, with different capabilities, - // upper bound the values according to the data from https://developer.apple.com/graphicsimaging/opengl/capabilities/ - max_texture_size = MIN(8192, max_texture_size); - max_array_texture_layers = MIN(512, max_array_texture_layers); -#endif + if (max_texture_size || !gpu_driver.initialized) return; + GPUCapabilities caps; + gpu_get_capabilities(&caps); + max_texture_size = (int32_t)caps.max_texture_size; + max_array_texture_layers = (int32_t)caps.max_array_texture_layers; sprite_tracker_set_limits(max_texture_size, max_array_texture_layers); } @@ -155,127 +151,15 @@ free_sprite_data(FONTS_DATA_HANDLE fg) { } } - -static void -discard_pending_gl_errors(void) { - // glad's error checking callback is installed only with --debug-rendering, - // so in normal runs errors queue up silently. Drain the queue so that a - // subsequent glGetError() reports only what we are interested in. - for (unsigned i = 0; i < 16 && glGetError() != GL_NO_ERROR; i++); +static gpu_texture_t +create_texture_or_die(const GPUTextureDesc *desc, const GPUPixelData *initial) { + gpu_texture_t ans = gpu_texture_create(desc, initial); + if (!ans) fatal("Failed to create a GPU texture with error: %s", gpu_last_error()); + return ans; } static bool -copy_texture_via_framebuffer(GLuint old_texture, GLuint new_texture, GLenum texture_type, GLint width, GLint height, GLint layers) { - GLint prev_read_fbo; - glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &prev_read_fbo); - discard_pending_gl_errors(); - GLuint fbo; - glGenFramebuffers(1, &fbo); - glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo); - bool ok = true; - for (GLint z = 0; z < layers && ok; z++) { - if (texture_type == GL_TEXTURE_2D_ARRAY) glFramebufferTextureLayer(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, old_texture, 0, z); - else glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, old_texture, 0); - ok = glCheckFramebufferStatus(GL_READ_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE; - if (!ok) break; - glBindTexture(texture_type, new_texture); - if (texture_type == GL_TEXTURE_2D_ARRAY) glCopyTexSubImage3D(texture_type, 0, 0, 0, z, 0, 0, width, height); - else glCopyTexSubImage2D(texture_type, 0, 0, 0, 0, 0, width, height); - // A complete framebuffer does not mean the copy itself was accepted, - // for instance if the two internal formats are not copy compatible. - // Without this check we would claim success and leave the new texture - // blank, losing every already rendered sprite. - ok = glGetError() == GL_NO_ERROR; - } - glBindFramebuffer(GL_READ_FRAMEBUFFER, prev_read_fbo); - glDeleteFramebuffers(1, &fbo); - if (!ok) glBindTexture(texture_type, old_texture); - return ok; -} - -static void -copy_32bit_texture(GLuint old_texture, GLuint new_texture, GLenum texture_type) { - // requires new texture to be at least as big as old texture. Assumes textures are 32bits per pixel - GLint width, height, layers; - glBindTexture(texture_type, old_texture); - glGetTexLevelParameteriv(texture_type, 0, GL_TEXTURE_WIDTH, &width); - glGetTexLevelParameteriv(texture_type, 0, GL_TEXTURE_HEIGHT, &height); - glGetTexLevelParameteriv(texture_type, 0, GL_TEXTURE_DEPTH, &layers); - if (GLAD_GL_ARB_copy_image) { - glCopyImageSubData(old_texture, texture_type, 0, 0, 0, 0, new_texture, texture_type, 0, 0, 0, 0, width, height, layers); - return; - } - if (copy_texture_via_framebuffer(old_texture, new_texture, texture_type, width, height, layers)) return; - - static bool copy_image_warned = false; - // Neither ARB_copy_image nor a framebuffer copy is usable, do a slow roundtrip copy - if (!copy_image_warned) { - copy_image_warned = true; - log_error("WARNING: Your system's OpenGL implementation cannot copy between textures on the GPU, falling back to a slower implementation"); - } - - GLint internal_format; - glGetTexLevelParameteriv(texture_type, 0, GL_TEXTURE_INTERNAL_FORMAT, &internal_format); - GLenum format, type; - switch (internal_format) { - case GL_R8UI: - case GL_R8I: - case GL_R16UI: - case GL_R16I: - case GL_R32UI: - case GL_R32I: - case GL_RG8UI: - case GL_RG8I: - case GL_RG16UI: - case GL_RG16I: - case GL_RG32UI: - case GL_RG32I: - case GL_RGB8UI: - case GL_RGB8I: - case GL_RGB16UI: - case GL_RGB16I: - case GL_RGB32UI: - case GL_RGB32I: - case GL_RGBA8UI: - case GL_RGBA8I: - case GL_RGBA16UI: - case GL_RGBA16I: - case GL_RGBA32UI: - case GL_RGBA32I: - format = GL_RED_INTEGER; - type = GL_UNSIGNED_INT; - break; - default: - format = GL_RGBA; - type = GL_UNSIGNED_INT_8_8_8_8; - break; - } - glPixelStorei(GL_UNPACK_ALIGNMENT, 4); - RAII_ALLOC(uint8_t, pixels, malloc((size_t)width * height * layers * 4u)); - if (!pixels) fatal("Out of memory"); - glGetTexImage(texture_type, 0, format, type, pixels); - glBindTexture(texture_type, new_texture); - glPixelStorei(GL_PACK_ALIGNMENT, 4); - if (texture_type == GL_TEXTURE_2D_ARRAY) glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, 0, width, height, layers, format, type, pixels); - else glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, pixels); -} - -static GLuint -setup_new_sprites_texture(GLenum texture_type) { - GLuint tex; - glGenTextures(1, &tex); - glBindTexture(texture_type, tex); - // We use GL_NEAREST otherwise glyphs that touch the edge of the cell - // often show a border between cells - glTexParameteri(texture_type, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(texture_type, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(texture_type, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(texture_type, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - return tex; -} - -static bool -decorations_map_new_size(size_t count, size_t current_capacity, size_t max_size, GLint *width, GLint *height) { +decorations_map_new_size(size_t count, size_t current_capacity, size_t max_size, int32_t *width, int32_t *height) { const size_t max_capacity = max_size * max_size; if (count >= max_capacity) return false; size_t capacity = MAX(MAX(count + 256, current_capacity * 2), (size_t)4096); @@ -296,17 +180,18 @@ realloc_sprite_decorations_texture_if_needed(FONTS_DATA_HANDLE fg) { SpriteMap *sm = (SpriteMap *)fg->sprite_map; size_t current_capacity = (size_t)dm.width * dm.height; if (dm.count < current_capacity && dm.texture_id) return; - GLint width, height; + int32_t width, height; if (!decorations_map_new_size(dm.count, current_capacity, sm->max_texture_size, &width, &height)) - fatal("Max texture size too small for sprite decorations map, maybe switch to using a GL_TEXTURE_2D_ARRAY"); - const GLenum texture_type = GL_TEXTURE_2D; - GLuint tex = setup_new_sprites_texture(texture_type); - glTexImage2D(texture_type, 0, GL_R32UI, width, height, 0, GL_RED_INTEGER, GL_UNSIGNED_INT, NULL); + fatal("Max texture size too small for sprite decorations map, maybe switch to using a GPU_TEXTURE_2D_ARRAY"); + // We use nearest filtering otherwise glyphs that touch the edge of the cell + // often show a border between cells + const GPUTextureDesc desc = { + .kind = GPU_TEXTURE_2D, .format = GPU_FORMAT_R32UI, .width = width, .height = height, .filter = GPU_FILTER_NEAREST, .wrap = GPU_WRAP_CLAMP_TO_EDGE}; + gpu_texture_t tex = create_texture_or_die(&desc, NULL); if (dm.texture_id) { // copy data from old texture - copy_32bit_texture(dm.texture_id, tex, texture_type); + gpu_texture_copy(dm.texture_id, tex); free_texture(&dm.texture_id); } - glBindTexture(texture_type, 0); dm.texture_id = tex; dm.width = width; dm.height = height; @@ -321,19 +206,32 @@ realloc_sprite_texture(FONTS_DATA_HANDLE fg) { SpriteMap *sprite_map = (SpriteMap *)fg->sprite_map; width = xnum * fg->fcm.cell_width; height = ynum * (fg->fcm.cell_height + 1); - const GLenum texture_type = GL_TEXTURE_2D_ARRAY; - GLuint tex = setup_new_sprites_texture(texture_type); - glTexStorage3D(texture_type, 1, GL_SRGB8_ALPHA8, width, height, znum); + // We use nearest filtering otherwise glyphs that touch the edge of the cell + // often show a border between cells + const GPUTextureDesc desc = { + .kind = GPU_TEXTURE_2D_ARRAY, + .format = GPU_FORMAT_SRGB8_ALPHA8, + .width = width, + .height = height, + .layers = znum, + .filter = GPU_FILTER_NEAREST, + .wrap = GPU_WRAP_CLAMP_TO_EDGE}; + gpu_texture_t tex = create_texture_or_die(&desc, NULL); if (sprite_map->texture_id) { // copy old texture data into new texture - copy_32bit_texture(sprite_map->texture_id, tex, texture_type); + gpu_texture_copy(sprite_map->texture_id, tex); free_texture(&sprite_map->texture_id); } - glBindTexture(texture_type, 0); sprite_map->last_num_of_layers = znum; sprite_map->last_ynum = ynum; sprite_map->texture_id = tex; } +static void +bind_sprite_map(const SpriteMap *sprite_map) { + gpu_bind_texture(SPRITE_DECORATIONS_MAP_UNIT, sprite_map->decorations_map.texture_id); + gpu_bind_texture(SPRITE_MAP_UNIT, sprite_map->texture_id); +} + static void ensure_sprite_map(FONTS_DATA_HANDLE fg) { SpriteMap *sprite_map = (SpriteMap *)fg->sprite_map; @@ -341,10 +239,7 @@ ensure_sprite_map(FONTS_DATA_HANDLE fg) { if (!sprite_map->decorations_map.texture_id) realloc_sprite_decorations_texture_if_needed(fg); // We have to rebind since we don't know if the texture was ever bound // in the context of the current OSWindow - glActiveTexture(GL_TEXTURE0 + SPRITE_DECORATIONS_MAP_UNIT); - glBindTexture(GL_TEXTURE_2D, sprite_map->decorations_map.texture_id); - glActiveTexture(GL_TEXTURE0 + SPRITE_MAP_UNIT); - glBindTexture(GL_TEXTURE_2D_ARRAY, sprite_map->texture_id); + bind_sprite_map(sprite_map); } void @@ -357,46 +252,49 @@ send_sprite_to_gpu(FONTS_DATA_HANDLE fg, sprite_index idx, pixel *buf, sprite_in div_t d = div(idx, dm.width); x = d.rem; y = d.quot; - glActiveTexture(GL_TEXTURE0 + SPRITE_DECORATIONS_MAP_UNIT); - glBindTexture(GL_TEXTURE_2D, dm.texture_id); - glPixelStorei(GL_UNPACK_ALIGNMENT, 4); - glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, 1, 1, GL_RED_INTEGER, GL_UNSIGNED_INT, &decoration_idx); + const GPUPixelData decoration_pixels = {.layout = GPU_PIXELS_R32UI, .row_alignment = 4, .data = &decoration_idx}; + gpu_texture_upload(dm.texture_id, x, y, 0, 1, 1, &decoration_pixels); #undef dm sprite_tracker_current_layout(fg, &xnum, &ynum, &znum); if ((int)znum >= sprite_map->last_num_of_layers || (znum == 0 && (int)ynum > sprite_map->last_ynum)) { realloc_sprite_texture(fg); sprite_tracker_current_layout(fg, &xnum, &ynum, &znum); } - glActiveTexture(GL_TEXTURE0 + SPRITE_MAP_UNIT); - glBindTexture(GL_TEXTURE_2D_ARRAY, sprite_map->texture_id); - glPixelStorei(GL_UNPACK_ALIGNMENT, 4); sprite_index_to_pos(idx, xnum, ynum, &x, &y, &z); x *= fg->fcm.cell_width; y *= (fg->fcm.cell_height + 1); - glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, x, y, z, fg->fcm.cell_width, fg->fcm.cell_height + 1, 1, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, buf); + const GPUPixelData sprite_pixels = {.layout = GPU_PIXELS_RGBA8_PACKED, .row_alignment = 4, .data = buf}; + gpu_texture_upload(sprite_map->texture_id, x, y, z, fg->fcm.cell_width, fg->fcm.cell_height + 1, &sprite_pixels); + // Sprites are sent while preparing to render, after ensure_sprite_map(), + // and the sprite textures may have been re-allocated, so rebind them. + bind_sprite_map(sprite_map); +} + +static void +define_texture(gpu_texture_t *tex_id, const GPUTextureDesc *desc, const GPUPixelData *pixels) { + if (*tex_id) { + if (!gpu_texture_reset(*tex_id, desc, pixels)) fatal("Failed to re-allocate GPU texture with error: %s", gpu_last_error()); + } else *tex_id = create_texture_or_die(desc, pixels); } void -send_image_to_gpu(GLuint *tex_id, const void *data, GLsizei width, GLsizei height, bool is_opaque, bool is_4byte_aligned, bool linear, RepeatStrategy repeat) { - if (!(*tex_id)) { glGenTextures(1, tex_id); } - glBindTexture(GL_TEXTURE_2D, *tex_id); - glPixelStorei(GL_UNPACK_ALIGNMENT, is_4byte_aligned ? 4 : 1); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, linear ? GL_LINEAR : GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, linear ? GL_LINEAR : GL_NEAREST); - RepeatStrategy r; +send_image_to_gpu( + gpu_texture_t *tex_id, const void *data, int32_t width, int32_t height, bool is_opaque, bool is_4byte_aligned, bool linear, RepeatStrategy repeat) { + GPUWrap wrap; switch (repeat) { - case REPEAT_MIRROR: r = GL_MIRRORED_REPEAT; break; - case REPEAT_CLAMP: { - static const GLfloat border_color[4] = {0}; - glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border_color); - r = GL_CLAMP_TO_BORDER; - break; - } - default: r = GL_REPEAT; + case REPEAT_MIRROR: wrap = GPU_WRAP_MIRRORED_REPEAT; break; + case REPEAT_CLAMP: wrap = GPU_WRAP_CLAMP_TO_BORDER; break; + default: wrap = GPU_WRAP_REPEAT; } - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, r); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, r); - glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB_ALPHA, width, height, 0, is_opaque ? GL_RGB : GL_RGBA, GL_UNSIGNED_BYTE, data); + const GPUTextureDesc desc = { + .kind = GPU_TEXTURE_2D, + .format = GPU_FORMAT_SRGB8_ALPHA8, + .width = width, + .height = height, + .filter = linear ? GPU_FILTER_LINEAR : GPU_FILTER_NEAREST, + .wrap = wrap}; + const GPUPixelData pixels = {.layout = is_opaque ? GPU_PIXELS_RGB8 : GPU_PIXELS_RGBA8, .row_alignment = is_4byte_aligned ? 4 : 1, .data = data}; + define_texture(tex_id, &desc, &pixels); } // Indexed color images are stored as integer textures with the palette index @@ -404,16 +302,17 @@ send_image_to_gpu(GLuint *tex_id, const void *data, GLsizei width, GLsizei heigh // Integer textures cannot be filtered, the shader does its own filtering after // the palette lookup. void -send_indexed_image_to_gpu(GLuint *tex_id, const void *data, GLsizei width, GLsizei height, unsigned bytes_per_pixel, bool is_4byte_aligned) { - if (!(*tex_id)) { glGenTextures(1, tex_id); } - glBindTexture(GL_TEXTURE_2D, *tex_id); - glPixelStorei(GL_UNPACK_ALIGNMENT, is_4byte_aligned ? 4 : 1); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); +send_indexed_image_to_gpu(gpu_texture_t *tex_id, const void *data, int32_t width, int32_t height, unsigned bytes_per_pixel, bool is_4byte_aligned) { const bool has_alpha = bytes_per_pixel == 2; - glTexImage2D(GL_TEXTURE_2D, 0, has_alpha ? GL_RG8UI : GL_R8UI, width, height, 0, has_alpha ? GL_RG_INTEGER : GL_RED_INTEGER, GL_UNSIGNED_BYTE, data); + const GPUTextureDesc desc = { + .kind = GPU_TEXTURE_2D, + .format = has_alpha ? GPU_FORMAT_RG8UI : GPU_FORMAT_R8UI, + .width = width, + .height = height, + .filter = GPU_FILTER_NEAREST, + .wrap = GPU_WRAP_CLAMP_TO_EDGE}; + const GPUPixelData pixels = {.layout = has_alpha ? GPU_PIXELS_RG8 : GPU_PIXELS_R8, .row_alignment = is_4byte_aligned ? 4 : 1, .data = data}; + define_texture(tex_id, &desc, &pixels); } // }}} @@ -445,8 +344,8 @@ draw_rounded_rect( color_vec4(program_uniform_location(ROUNDED_RECT_PROGRAM, "outer_color"), srgb_outer, outer_alpha); // y co-ord has to be changed to co-ord system with origin at bottom left float y = (float)framebuffer_height - (float)(rect.top + rect.height); - glUniform4f(program_uniform_location(ROUNDED_RECT_PROGRAM, "rect"), rect.left, y, rect.width, rect.height); - glUniform2f(program_uniform_location(ROUNDED_RECT_PROGRAM, "params"), thickness, corner_radius_px); + gpu_uniform4f(program_uniform_location(ROUNDED_RECT_PROGRAM, "rect"), rect.left, y, rect.width, rect.height); + gpu_uniform2f(program_uniform_location(ROUNDED_RECT_PROGRAM, "params"), thickness, corner_radius_px); save_viewport_using_top_left_origin(rect.left, rect.top, rect.width, rect.height, framebuffer_height); draw_quad(true, 0); restore_viewport(); @@ -507,14 +406,15 @@ static struct { } custom_shaders; static struct { - GLuint texture_id, framebuffer_id; + gpu_texture_t texture_id; + gpu_render_target_t framebuffer_id; } pointer_map_target; static void -write_uint_array_to_ubo(void *dest, const GLuint *src, size_t count, const ArrayInformation *ai) { - GLint stride = MAX((GLint)sizeof(GLuint), ai->stride); +write_uint_array_to_ubo(void *dest, const uint32_t *src, size_t count, const ArrayInformation *ai) { + int32_t stride = MAX((int32_t)sizeof(uint32_t), ai->stride); uint8_t *buf = (uint8_t *)dest + ai->offset; - for (size_t i = 0; i < count; i++, buf += stride) memcpy(buf, src + i, sizeof(GLuint)); + for (size_t i = 0; i < count; i++, buf += stride) memcpy(buf, src + i, sizeof(uint32_t)); } // The gamma LUT is a compile time constant that lives in the default uniform @@ -529,11 +429,11 @@ write_uint_array_to_ubo(void *dest, const GLuint *src, size_t count, const Array // See https://github.com/kovidgoyal/kitty/issues/10571 void upload_gamma_lut(void) { -#define U(program) \ - { \ - bind_program(program); \ - GLint loc = program_uniform_location(program, "gamma_lut"); \ - if (loc >= 0) glUniform1fv(loc, arraysz(srgb_lut), srgb_lut); \ +#define U(program) \ + { \ + bind_program(program); \ + int32_t loc = program_uniform_location(program, "gamma_lut"); \ + if (loc >= 0) gpu_set_uniform_floats(loc, 1, arraysz(srgb_lut), srgb_lut); \ } for (int i = CELL_PROGRAM; i < CELL_PROGRAM_SENTINEL; i++) U(i); U(BORDERS_PROGRAM); @@ -548,9 +448,9 @@ static void init_cell_program(void) { for (int i = CELL_PROGRAM; i < CELL_PROGRAM_SENTINEL; i++) { UniformBlock crd = program_uniform_block(i, "CellRenderData"); - glUniformBlockBinding(program_id(i), crd.index, CELL_RENDER_DATA_BINDING_POINT); + gpu_pipeline_bind_uniform_block(program_pipeline(i), (uint32_t)crd.index, CELL_RENDER_DATA_BINDING_POINT); UniformBlock ct = program_uniform_block(i, "ColorTable"); - glUniformBlockBinding(program_id(i), ct.index, COLOR_TABLE_BINDING_POINT); + gpu_pipeline_bind_uniform_block(program_pipeline(i), (uint32_t)ct.index, COLOR_TABLE_BINDING_POINT); } // Sanity check to ensure the attribute location binding worked @@ -567,15 +467,15 @@ init_cell_program(void) { } #undef C UniformBlock border_colors = program_uniform_block(BORDERS_PROGRAM, "Colors"); - glUniformBlockBinding(program_id(BORDERS_PROGRAM), border_colors.index, BORDER_COLORS_BINDING_POINT); + gpu_pipeline_bind_uniform_block(program_pipeline(BORDERS_PROGRAM), (uint32_t)border_colors.index, BORDER_COLORS_BINDING_POINT); // The padding program shares the cell background computation and so uses the // same uniform blocks bound to the same binding points as the cell programs. { UniformBlock crd = program_uniform_block(PADDING_PROGRAM, "CellRenderData"); - glUniformBlockBinding(program_id(PADDING_PROGRAM), crd.index, CELL_RENDER_DATA_BINDING_POINT); + gpu_pipeline_bind_uniform_block(program_pipeline(PADDING_PROGRAM), (uint32_t)crd.index, CELL_RENDER_DATA_BINDING_POINT); UniformBlock ct = program_uniform_block(PADDING_PROGRAM, "ColorTable"); - glUniformBlockBinding(program_id(PADDING_PROGRAM), ct.index, COLOR_TABLE_BINDING_POINT); + gpu_pipeline_bind_uniform_block(program_pipeline(PADDING_PROGRAM), (uint32_t)ct.index, COLOR_TABLE_BINDING_POINT); } #define C(name, expected) \ { \ @@ -589,14 +489,14 @@ init_cell_program(void) { // Indexed color images get their colors from the color table of the window they are in for (int i = GRAPHICS_INDEXED_PROGRAM; i <= GRAPHICS_INDEXED_UNSCALED_PROGRAM; i++) { UniformBlock ct = program_uniform_block(i, "ColorTable"); - glUniformBlockBinding(program_id(i), ct.index, COLOR_TABLE_BINDING_POINT); + gpu_pipeline_bind_uniform_block(program_pipeline(i), (uint32_t)ct.index, COLOR_TABLE_BINDING_POINT); } if (shader_globals_vao_idx == -1) { shader_globals_vao_idx = create_vao(); - add_buffer_to_vao(shader_globals_vao_idx, GL_UNIFORM_BUFFER); + add_buffer_to_vao(shader_globals_vao_idx, GPU_BUFFER_UNIFORM); // The border colors change on every draw, but are shared amongst all border VAOs (only one is ever drawn at a time) - alloc_vao_buffer(shader_globals_vao_idx, border_colors.size, BORDER_COLORS_GLOBAL_BUFFER, GL_STREAM_DRAW); + alloc_vao_buffer(shader_globals_vao_idx, border_colors.size, BORDER_COLORS_GLOBAL_BUFFER, GPU_UPDATE_EVERY_USE); } upload_gamma_lut(); bind_shader_globals_to_current_context(); @@ -741,23 +641,22 @@ static void init_custom_programs(void) { custom_shaders.count = 0; for (int i = CUSTOM_END_PROGRAM; i < NUM_PROGRAMS; i++) { - Program *p = program_ptr(i); - if (p && p->id) { + if (program_pipeline(i)) { custom_shaders.count++; if (i == CUSTOM_END_PROGRAM) { bind_program(i); - glUniform1i(program_uniform_location(i, "backbuffer"), GRAPHICS_UNIT); -#define set_optional_sampler(name, unit) \ - { \ - GLint loc = try_program_uniform_location(i, name); \ - if (loc >= 0) glUniform1i(loc, unit); \ + gpu_uniform1i(program_uniform_location(i, "backbuffer"), GRAPHICS_UNIT); +#define set_optional_sampler(name, unit) \ + { \ + int32_t loc = try_program_uniform_location(i, name); \ + if (loc >= 0) gpu_uniform1i(loc, unit); \ } set_optional_sampler("a", CUSTOM_END_TEXTURE_A_UNIT); set_optional_sampler("b", CUSTOM_END_TEXTURE_B_UNIT); set_optional_sampler("persist", CUSTOM_END_TEXTURE_PERSIST_UNIT); #undef set_optional_sampler - GLint group_loc = try_program_uniform_location(i, "group"); - if (group_loc >= 0) glUniform1i(group_loc, 0); + int32_t group_loc = try_program_uniform_location(i, "group"); + if (group_loc >= 0) gpu_uniform1i(group_loc, 0); else if (custom_shaders.end.num_groups > 1) { // Every group is dispatched by setting this uniform, so without it // all of them render as group zero, which for a multi pass pipeline @@ -768,11 +667,11 @@ init_custom_programs(void) { custom_shaders.end.num_groups); } UniformBlock ubd = program_uniform_block(i, "KittyCustomShaderData"); - glUniformBlockBinding(program_id(i), ubd.index, CUSTOM_END_DATA_BINDING_POINT); + gpu_pipeline_bind_uniform_block(program_pipeline(i), (uint32_t)ubd.index, CUSTOM_END_DATA_BINDING_POINT); if (custom_end_vao_idx == -1) { custom_end_vao_idx = create_vao(); - add_buffer_to_vao(custom_end_vao_idx, GL_UNIFORM_BUFFER); - alloc_vao_buffer(custom_end_vao_idx, ubd.size, 0, GL_STREAM_DRAW); + add_buffer_to_vao(custom_end_vao_idx, GPU_BUFFER_UNIFORM); + alloc_vao_buffer(custom_end_vao_idx, ubd.size, 0, GPU_UPDATE_EVERY_USE); } } } @@ -1052,23 +951,23 @@ create_cell_vao(void) { #define A(name, size, dtype, offset, stride) \ add_attribute_to_vao( \ vao_idx, program_attribute_location(CELL_PROGRAM, name), /*size=*/size, /*dtype=*/dtype, /*stride=*/stride, /*offset=*/offset, /*divisor=*/1); -#define A1(name, size, dtype, offset) A(name, size, dtype, (void *)(offsetof(GPUCell, offset)), sizeof(GPUCell)) +#define A1(name, size, dtype, offset) A(name, size, dtype, offsetof(GPUCell, offset), sizeof(GPUCell)) - add_buffer_to_vao(vao_idx, GL_ARRAY_BUFFER); - A1("sprite_idx", 2, GL_UNSIGNED_INT, sprite_idx); - A1("colors", 3, GL_UNSIGNED_INT, fg); + add_buffer_to_vao(vao_idx, GPU_BUFFER_VERTEX); + A1("sprite_idx", 2, GPU_ATTRIB_U32, sprite_idx); + A1("colors", 3, GPU_ATTRIB_U32, fg); - add_buffer_to_vao(vao_idx, GL_ARRAY_BUFFER); - A("is_selected", 1, GL_UNSIGNED_BYTE, NULL, 0); + add_buffer_to_vao(vao_idx, GPU_BUFFER_VERTEX); + A("is_selected", 1, GPU_ATTRIB_U8, 0, 0); - size_t bufnum = add_buffer_to_vao(vao_idx, GL_UNIFORM_BUFFER); - alloc_vao_buffer(vao_idx, program_uniform_block(CELL_PROGRAM, "CellRenderData").size, bufnum, GL_STREAM_DRAW); + size_t bufnum = add_buffer_to_vao(vao_idx, GPU_BUFFER_UNIFORM); + alloc_vao_buffer(vao_idx, program_uniform_block(CELL_PROGRAM, "CellRenderData").size, bufnum, GPU_UPDATE_EVERY_USE); - size_t ctbufnum = add_buffer_to_vao(vao_idx, GL_UNIFORM_BUFFER); - alloc_vao_buffer(vao_idx, program_uniform_block(CELL_PROGRAM, "ColorTable").size, ctbufnum, GL_STATIC_DRAW); + size_t ctbufnum = add_buffer_to_vao(vao_idx, GPU_BUFFER_UNIFORM); + alloc_vao_buffer(vao_idx, program_uniform_block(CELL_PROGRAM, "ColorTable").size, ctbufnum, GPU_UPDATE_RARELY); - add_buffer_to_vao(vao_idx, GL_ARRAY_BUFFER); // padding_cell_data_buffer (slot 4) - add_buffer_to_vao(vao_idx, GL_ARRAY_BUFFER); // padding_selection_buffer (slot 5) + add_buffer_to_vao(vao_idx, GPU_BUFFER_VERTEX); // padding_cell_data_buffer (slot 4) + add_buffer_to_vao(vao_idx, GPU_BUFFER_VERTEX); // padding_selection_buffer (slot 5) return vao_idx; #undef A @@ -1150,28 +1049,28 @@ cell_update_uniform_block( // space so the vertex shader does not do a gamma LUT lookup for them // once per vertex. These must come first and the fourth component of // each is unused padding, see CellRenderData in background.slang. - GLfloat default_fg_lin[4], default_bg_lin[4], highlight_fg_lin[4], highlight_bg_lin[4]; - GLfloat main_cursor_fg_lin[4], main_cursor_bg_lin[4], url_color_lin[4]; - GLfloat extra_cursor_fg_lin[4], extra_cursor_bg_lin[4]; + float default_fg_lin[4], default_bg_lin[4], highlight_fg_lin[4], highlight_bg_lin[4]; + float main_cursor_fg_lin[4], main_cursor_bg_lin[4], url_color_lin[4]; + float extra_cursor_fg_lin[4], extra_cursor_bg_lin[4]; - GLfloat use_cell_bg_for_selection_fg, use_cell_fg_for_selection_color, use_cell_for_selection_bg; + float use_cell_bg_for_selection_fg, use_cell_fg_for_selection_color, use_cell_for_selection_bg; - GLuint default_fg, url_style, inverted, main_cursor_is_special, extra_cursor_fg, extra_cursor_bg; + uint32_t default_fg, url_style, inverted, main_cursor_is_special, extra_cursor_fg, extra_cursor_bg; - GLuint columns, lines, sprites_xnum, sprites_ynum, cursor_shape, cell_width, cell_height; - GLuint cursor_x1, cursor_x2, cursor_y1, cursor_y2; - GLfloat cursor_opacity, inactive_text_alpha, fg_override_threshold, row_offset, dim_opacity, blink_opacity; + uint32_t columns, lines, sprites_xnum, sprites_ynum, cursor_shape, cell_width, cell_height; + uint32_t cursor_x1, cursor_x2, cursor_y1, cursor_y2; + float cursor_opacity, inactive_text_alpha, fg_override_threshold, row_offset, dim_opacity, blink_opacity; - GLuint bg_colors0, bg_colors1, bg_colors2, bg_colors3, bg_colors4, bg_colors5, bg_colors6, bg_colors7; - GLfloat bg_opacities0, bg_opacities1, bg_opacities2, bg_opacities3, bg_opacities4, bg_opacities5, bg_opacities6, bg_opacities7; + uint32_t bg_colors0, bg_colors1, bg_colors2, bg_colors3, bg_colors4, bg_colors5, bg_colors6, bg_colors7; + float bg_opacities0, bg_opacities1, bg_opacities2, bg_opacities3, bg_opacities4, bg_opacities5, bg_opacities6, bg_opacities7; }; // Send the uniform data ColorProfile *cp = screen->paused_rendering.expires_at ? &screen->paused_rendering.color_profile : screen->color_profile; if (cp->dirty || screen->reload_all_gpu_data) { const ArrayInformation ai = program_uniform_array(CELL_PROGRAM, "color_table"); uint8_t *base = (uint8_t *)map_vao_buffer_for_write_only(vao_idx, color_table_buf, 0, program_uniform_block(CELL_PROGRAM, "ColorTable").size); - GLuint *ct_buf = (GLuint *)(base + ai.offset); - copy_color_table_to_buffer(cp, ct_buf, 0, ai.stride / sizeof(GLuint)); + uint32_t *ct_buf = (uint32_t *)(base + ai.offset); + copy_color_table_to_buffer(cp, ct_buf, 0, ai.stride / sizeof(uint32_t)); unmap_vao_buffer(vao_idx, color_table_buf); } // This struct is a hand written mirror of the std140 layout of @@ -1409,26 +1308,25 @@ cell_prepare_to_render(ssize_t vao_idx, Screen *screen, FONTS_DATA_HANDLE fonts_ } static void -draw_graphics(int program, ImageRenderData *data, GLuint start, GLuint count, float extra_alpha) { +draw_graphics(int program, ImageRenderData *data, uint32_t start, uint32_t count, float extra_alpha) { bind_program(program); - if (program != GRAPHICS_ALPHA_MASK_PROGRAM) glUniform1f(program_uniform_location(program, "extra_alpha"), extra_alpha); - glActiveTexture(GL_TEXTURE0 + GRAPHICS_UNIT); - GLint src_rect_loc = program_uniform_location(program, "src_rect"); - GLint dest_rect_loc = program_uniform_location(program, "dest_rect"); + if (program != GRAPHICS_ALPHA_MASK_PROGRAM) gpu_uniform1f(program_uniform_location(program, "extra_alpha"), extra_alpha); + int32_t src_rect_loc = program_uniform_location(program, "src_rect"); + int32_t dest_rect_loc = program_uniform_location(program, "dest_rect"); const bool is_indexed = program == GRAPHICS_INDEXED_PROGRAM || program == GRAPHICS_INDEXED_UNSCALED_PROGRAM; - const GLint has_alpha_loc = is_indexed ? program_uniform_location(program, "has_alpha") : -1; - for (GLuint i = 0; i < count;) { + const int32_t has_alpha_loc = is_indexed ? program_uniform_location(program, "has_alpha") : -1; + for (uint32_t i = 0; i < count;) { ImageRenderData *group = data + start + i; - glBindTexture(GL_TEXTURE_2D, group->texture_id); - if (has_alpha_loc > -1) glUniform1ui(has_alpha_loc, group->indexed_px_sz == 2); + gpu_bind_texture(GRAPHICS_UNIT, group->texture_id); + if (has_alpha_loc > -1) gpu_uniform1ui(has_alpha_loc, group->indexed_px_sz == 2); if (group->group_count == 0) { i++; continue; } - for (GLuint k = 0; k < group->group_count; k++, i++) { + for (uint32_t k = 0; k < group->group_count; k++, i++) { ImageRenderData *rd = data + start + i; - glUniform4f(src_rect_loc, rd->src_rect.left, rd->src_rect.top, rd->src_rect.right, rd->src_rect.bottom); - glUniform4f(dest_rect_loc, rd->dest_rect.left, rd->dest_rect.top, rd->dest_rect.right, rd->dest_rect.bottom); + gpu_uniform4f(src_rect_loc, rd->src_rect.left, rd->src_rect.top, rd->src_rect.right, rd->src_rect.bottom); + gpu_uniform4f(dest_rect_loc, rd->dest_rect.left, rd->dest_rect.top, rd->dest_rect.right, rd->dest_rect.bottom); draw_quad(true, 0); } } @@ -1437,51 +1335,41 @@ draw_graphics(int program, ImageRenderData *data, GLuint start, GLuint count, fl static ImageRenderData * load_alpha_mask_texture(size_t width, size_t height, uint8_t *canvas) { static ImageRenderData data = {.group_count = 1}; - if (!data.texture_id) { glGenTextures(1, &data.texture_id); } - glBindTexture(GL_TEXTURE_2D, data.texture_id); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, canvas); + const GPUTextureDesc desc = { + .kind = GPU_TEXTURE_2D, .format = GPU_FORMAT_R8, .width = width, .height = height, .filter = GPU_FILTER_NEAREST, .wrap = GPU_WRAP_CLAMP_TO_EDGE}; + const GPUPixelData pixels = {.layout = GPU_PIXELS_R8, .row_alignment = 1, .data = canvas}; + define_texture(&data.texture_id, &desc, &pixels); return &data; } static void -setup_texture_as_render_target(unsigned width, unsigned height, GLuint *texture_id, GLuint *framebuffer_id) { - glGenTextures(1, texture_id); - glGenFramebuffers(1, framebuffer_id); - glBindTexture(GL_TEXTURE_2D, *texture_id); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - // We use GL_RGBA16 to avoid incorrect colors due to quantization loss when +setup_texture_as_render_target(unsigned width, unsigned height, gpu_texture_t *texture_id, gpu_render_target_t *framebuffer_id) { + // We use 16 bit color channels to avoid incorrect colors due to quantization loss when // blending, see https://github.com/kovidgoyal/kitty/issues/8953 static struct { bool ok; - int fmt; - } status = {false, GL_RGBA16}; - glTexImage2D(GL_TEXTURE_2D, 0, status.fmt, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); - bind_framebuffer_for_output(*framebuffer_id); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, *texture_id, 0); + GPUTextureFormat fmt; + } status = {false, GPU_FORMAT_RGBA16}; + const GPUTextureDesc desc = { + .kind = GPU_TEXTURE_2D, .format = status.fmt, .width = width, .height = height, .filter = GPU_FILTER_LINEAR, .wrap = GPU_WRAP_CLAMP_TO_EDGE}; + *texture_id = create_texture_or_die(&desc, NULL); + *framebuffer_id = gpu_render_target_create(*texture_id); + if (!*framebuffer_id) fatal("Failed to create a GPU render target with error: %s", gpu_last_error()); if (!status.ok) { - if (check_framebuffer_status() == NULL) { + if (gpu_render_target_status(*framebuffer_id) == NULL) { status.ok = true; } else { - if (status.fmt == GL_RGBA16) { - // Driver does not support 16 bit FBO so let it choose the - // format. It will probably end up choosing 8 bit but - // inaccurate colors are better than completely broken rendering. - // See https://github.com/kovidgoyal/kitty/issues/9068 - status.fmt = GL_RGBA; + if (status.fmt == GPU_FORMAT_RGBA16) { + // Driver does not support 16 bit render targets so fall back + // to 8 bit. Inaccurate colors are better than completely + // broken rendering. See https://github.com/kovidgoyal/kitty/issues/9068 + status.fmt = GPU_FORMAT_RGBA8; free_framebuffer(framebuffer_id); free_texture(texture_id); setup_texture_as_render_target(width, height, texture_id, framebuffer_id); log_error("WARNING: Your GPU driver does not support 16bit textures as framebuffer targets, some colors may be slightly inaccurate."); } else { - fatal("Your GPU driver does not support indirect rendering to a GL_RGBA texture via a framebuffer"); + fatal("Your GPU driver does not support indirect rendering to a RGBA texture via a framebuffer"); } } } @@ -1495,27 +1383,27 @@ set_cell_uniforms(bool force) { float text_gamma_adjustment = OPT(text_gamma_adjustment) < 0.01f ? 1.0f : 1.0f / OPT(text_gamma_adjustment); for (int i = GRAPHICS_PROGRAM; i <= GRAPHICS_INDEXED_UNSCALED_PROGRAM; i++) { bind_program(i); - glUniform1i(program_uniform_location(i, "image"), GRAPHICS_UNIT); + gpu_uniform1i(program_uniform_location(i, "image"), GRAPHICS_UNIT); } // These are set for every cell program, but the background program draws no // text and so does not have them. -#define set_optional(setter, name, value) \ - { \ - GLint loc = try_program_uniform_location(i, name); \ - if (loc >= 0) setter(loc, value); \ +#define set_optional(setter, name, value) \ + { \ + int32_t loc = try_program_uniform_location(i, name); \ + if (loc >= 0) setter(loc, value); \ } for (int i = CELL_PROGRAM; i < CELL_PROGRAM_SENTINEL; i++) { bind_program(i); - set_optional(glUniform1i, "sprites", SPRITE_MAP_UNIT); - set_optional(glUniform1i, "sprite_decorations_map", SPRITE_DECORATIONS_MAP_UNIT); - set_optional(glUniform1f, "text_contrast", text_contrast); - set_optional(glUniform1f, "text_gamma_adjustment", text_gamma_adjustment); + set_optional(gpu_uniform1i, "sprites", SPRITE_MAP_UNIT); + set_optional(gpu_uniform1i, "sprite_decorations_map", SPRITE_DECORATIONS_MAP_UNIT); + set_optional(gpu_uniform1f, "text_contrast", text_contrast); + set_optional(gpu_uniform1f, "text_gamma_adjustment", text_gamma_adjustment); } #undef set_optional bind_program(BLIT_PROGRAM); - glUniform1i(program_uniform_location(BLIT_PROGRAM, "image"), GRAPHICS_UNIT); + gpu_uniform1i(program_uniform_location(BLIT_PROGRAM, "image"), GRAPHICS_UNIT); bind_program(SCREENSHOT_PROGRAM); - glUniform1i(program_uniform_location(SCREENSHOT_PROGRAM, "image"), GRAPHICS_UNIT); + gpu_uniform1i(program_uniform_location(SCREENSHOT_PROGRAM, "image"), GRAPHICS_UNIT); constants_set = true; } } @@ -1545,18 +1433,18 @@ get_visual_bell_intensity(Screen *screen) { } static void -draw_visual_bell_flash(GLfloat intensity, const color_type flash) { +draw_visual_bell_flash(float intensity, const color_type flash) { bind_program(TINT_PROGRAM); - GLfloat attenuation = 0.4f; + float attenuation = 0.4f; #define C(shift) srgb_color((flash >> shift) & 0xFF) - const GLfloat r = C(16), g = C(8), b = C(0); - const GLfloat max_channel = r > g ? (r > b ? r : b) : (g > b ? g : b); + const float r = C(16), g = C(8), b = C(0); + const float max_channel = r > g ? (r > b ? r : b) : (g > b ? g : b); #undef C #define C(x) (x * intensity * attenuation) if (max_channel > 0.45) attenuation = 0.6f; // light color - glUniform4f(program_uniform_location(TINT_PROGRAM, "tint_color"), C(r), C(g), C(b), C(1)); + gpu_uniform4f(program_uniform_location(TINT_PROGRAM, "tint_color"), C(r), C(g), C(b), C(1)); #undef C - glUniform4f(program_uniform_location(TINT_PROGRAM, "edges"), -1, 1, 1, -1); + gpu_uniform4f(program_uniform_location(TINT_PROGRAM, "edges"), -1, 1, 1, -1); draw_quad(true, 0); } @@ -1589,7 +1477,7 @@ draw_drag_preview_overlay(const UIRenderData *ui) { const monotonic_t elapsed = monotonic() - screen->start_drag_overlay_at; const monotonic_t fade_ms = ms_to_monotonic_t(150ll); float intensity = elapsed >= fade_ms ? 1.0f : (float)elapsed / (float)fade_ms; - GLfloat left = -1.f, top = 1.f, right = 1.f, bottom = -1.f; + float left = -1.f, top = 1.f, right = 1.f, bottom = -1.f; switch (screen->drag_overlay_quadrant) { case 1: right = 0.f; break; // left half case 2: left = 0.f; break; // right half @@ -1603,9 +1491,9 @@ draw_drag_preview_overlay(const UIRenderData *ui) { float a = intensity * 0.25f; color_type hint = get_flash_color(screen); #define C(shift) (srgb_color((hint >> shift) & 0xFF) * a) - glUniform4f(program_uniform_location(TINT_PROGRAM, "tint_color"), C(16), C(8), C(0), a); + gpu_uniform4f(program_uniform_location(TINT_PROGRAM, "tint_color"), C(16), C(8), C(0), a); #undef C - glUniform4f(program_uniform_location(TINT_PROGRAM, "edges"), left, top, right, bottom); + gpu_uniform4f(program_uniform_location(TINT_PROGRAM, "edges"), left, top, right, bottom); draw_quad(true, 0); } @@ -1691,14 +1579,15 @@ draw_bar(const UIRenderData *ui, const WindowBarData *bar, Viewport border_rect, const float drawn_thickness = (float)MIN(thickness, border_width - 0.5); static ImageRenderData data = {.group_count = 1}; gpu_data_for_image(&data, -1, 1, 1, -1); - glGenTextures(1, &data.texture_id); - glBindTexture(GL_TEXTURE_2D, data.texture_id); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB_ALPHA, bar->width, bar->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, bar->buf); + const GPUTextureDesc desc = { + .kind = GPU_TEXTURE_2D, + .format = GPU_FORMAT_SRGB8_ALPHA8, + .width = bar->width, + .height = bar->height, + .filter = GPU_FILTER_NEAREST, + .wrap = GPU_WRAP_CLAMP_TO_EDGE}; + const GPUPixelData pixels = {.layout = GPU_PIXELS_RGBA8, .row_alignment = 1, .data = bar->buf}; + data.texture_id = create_texture_or_die(&desc, &pixels); bind_program(GRAPHICS_PROGRAM); const unsigned sh = ui->full_framebuffer_height; // first blank the area to be drawn to background @@ -1839,7 +1728,7 @@ draw_window_number(const UIRenderData *ui) { bind_program(GRAPHICS_ALPHA_MASK_PROGRAM); ImageRenderData *ird = load_alpha_mask_texture(lr.width_px, lr.height_px, lr.canvas); gpu_data_for_image(ird, -1, 1, 1, -1); - glUniform1i(program_uniform_location(GRAPHICS_ALPHA_MASK_PROGRAM, "image"), GRAPHICS_UNIT); + gpu_uniform1i(program_uniform_location(GRAPHICS_ALPHA_MASK_PROGRAM, "image"), GRAPHICS_UNIT); color_type digit_color = colorprofile_to_color_with_fallback( ui->screen->color_profile, ui->screen->color_profile->overridden.highlight_bg, @@ -1847,7 +1736,7 @@ draw_window_number(const UIRenderData *ui) { ui->screen->color_profile->overridden.default_fg, ui->screen->color_profile->configured.default_fg); color_vec3(program_uniform_location(GRAPHICS_ALPHA_MASK_PROGRAM, "amask_fg"), digit_color); - glUniform4f(program_uniform_location(GRAPHICS_ALPHA_MASK_PROGRAM, "amask_bg_premult"), 0.f, 0.f, 0.f, 0.f); + gpu_uniform4f(program_uniform_location(GRAPHICS_ALPHA_MASK_PROGRAM, "amask_bg_premult"), 0.f, 0.f, 0.f, 0.f); save_viewport_using_top_left_origin(ui->screen_left + letter_x, ui->screen_top + letter_y, lr.width_px, lr.height_px, ui->full_framebuffer_height); draw_graphics(GRAPHICS_ALPHA_MASK_PROGRAM, ird, 0, 1, 1.f); restore_viewport(); @@ -1860,7 +1749,7 @@ set_color_uniform_with_opacity(color_type color, float opacity) { float r = srgb_color((color >> 16) & 0xFF) * opacity; float g = srgb_color((color >> 8) & 0xFF) * opacity; float b = srgb_color(color & 0xFF) * opacity; - glUniform4f(program_uniform_location(TINT_PROGRAM, "tint_color"), r, g, b, opacity); + gpu_uniform4f(program_uniform_location(TINT_PROGRAM, "tint_color"), r, g, b, opacity); } static color_type @@ -1885,20 +1774,20 @@ draw_scrollbar(const UIRenderData *ui) { screen_scrollbar_geometry(screen, &bar_frac, &visible_fraction); float opacity = OPT(scrollbar_handle_opacity); float track_opacity = window->scrollbar.is_hovering ? OPT(scrollbar_track_hover_opacity) : OPT(scrollbar_track_opacity); - GLsizei scrollbar_width_px = (GLsizei)(OPT(scrollbar_width) * ui->cell_width); - if (window->scrollbar.is_hovering) scrollbar_width_px = (GLsizei)(OPT(scrollbar_hover_width) * ui->cell_width); - GLsizei scrollbar_gap_px = (GLsizei)(OPT(scrollbar_gap) * ui->cell_width); + int32_t scrollbar_width_px = (int32_t)(OPT(scrollbar_width) * ui->cell_width); + if (window->scrollbar.is_hovering) scrollbar_width_px = (int32_t)(OPT(scrollbar_hover_width) * ui->cell_width); + int32_t scrollbar_gap_px = (int32_t)(OPT(scrollbar_gap) * ui->cell_width); unsigned scrollbar_radius = (unsigned)(OPT(scrollbar_radius) * ui->cell_width); // Calculate window boundaries including padding - GLsizei window_right_edge = ui->screen_left + ui->screen_width + window->render_data.geometry.spaces.right; - GLsizei window_top_edge = ui->screen_top - window->render_data.geometry.spaces.top; - GLsizei window_height = ui->screen_height + window->render_data.geometry.spaces.top + window->render_data.geometry.spaces.bottom; + int32_t window_right_edge = ui->screen_left + ui->screen_width + window->render_data.geometry.spaces.right; + int32_t window_top_edge = ui->screen_top - window->render_data.geometry.spaces.top; + int32_t window_height = ui->screen_height + window->render_data.geometry.spaces.top + window->render_data.geometry.spaces.bottom; // Position scrollbar on right side with gap - GLsizei scrollbar_left = window_right_edge - scrollbar_width_px - scrollbar_gap_px; - GLsizei scrollbar_top = window_top_edge + scrollbar_gap_px; - GLsizei scrollbar_height = window_height - 2 * scrollbar_gap_px; + int32_t scrollbar_left = window_right_edge - scrollbar_width_px - scrollbar_gap_px; + int32_t scrollbar_top = window_top_edge + scrollbar_gap_px; + int32_t scrollbar_height = window_height - 2 * scrollbar_gap_px; // Calculate thumb size and position float min_thumb_height_fraction = (OPT(scrollbar_min_handle_height) * ui->cell_height) / (float)window_height; @@ -1926,15 +1815,15 @@ draw_scrollbar(const UIRenderData *ui) { if (track_opacity > 0) { bind_program(TINT_PROGRAM); set_color_uniform_with_opacity(track_color, track_opacity); - glUniform4f(program_uniform_location(TINT_PROGRAM, "edges"), -1.f, 1.f, 1.f, -1.f); + gpu_uniform4f(program_uniform_location(TINT_PROGRAM, "edges"), -1.f, 1.f, 1.f, -1.f); draw_quad(true, 0); } // Draw scrollbar thumb (handle) if (scrollbar_radius > 0) { // Rounded thumb - use separate viewport and rounded rect program - GLsizei thumb_height_px = (GLsizei)(thumb_height_fraction * scrollbar_height); - GLsizei thumb_top_px = scrollbar_top + (GLsizei)(thumb_top_fraction * scrollbar_height); + int32_t thumb_height_px = (int32_t)(thumb_height_fraction * scrollbar_height); + int32_t thumb_top_px = scrollbar_top + (int32_t)(thumb_top_fraction * scrollbar_height); restore_viewport(); @@ -1944,17 +1833,17 @@ draw_scrollbar(const UIRenderData *ui) { color_vec4(program_uniform_location(ROUNDED_RECT_PROGRAM, "outer_color"), 0, 0.0f); float y = (float)ui->full_framebuffer_height - (float)(thumb_top_px + thumb_height_px); - glUniform4f(program_uniform_location(ROUNDED_RECT_PROGRAM, "rect"), (float)scrollbar_left, y, (float)scrollbar_width_px, (float)thumb_height_px); + gpu_uniform4f(program_uniform_location(ROUNDED_RECT_PROGRAM, "rect"), (float)scrollbar_left, y, (float)scrollbar_width_px, (float)thumb_height_px); float thickness = (float)MAX(scrollbar_width_px, thumb_height_px); - glUniform2f(program_uniform_location(ROUNDED_RECT_PROGRAM, "params"), thickness, (float)scrollbar_radius); + gpu_uniform2f(program_uniform_location(ROUNDED_RECT_PROGRAM, "params"), thickness, (float)scrollbar_radius); save_viewport_using_top_left_origin(scrollbar_left, thumb_top_px, scrollbar_width_px, thumb_height_px, ui->full_framebuffer_height); draw_quad(true, 0); restore_viewport(); } else { set_color_uniform_with_opacity(bar_color, opacity); - glUniform4f(program_uniform_location(TINT_PROGRAM, "edges"), -1.f, thumb_top_gl, 1.f, thumb_bottom_gl); + gpu_uniform4f(program_uniform_location(TINT_PROGRAM, "edges"), -1.f, thumb_top_gl, 1.f, thumb_bottom_gl); draw_quad(true, 0); restore_viewport(); } @@ -1972,31 +1861,31 @@ draw_progress_handle( color_type bar_color, float opacity, unsigned bar_radius, - GLsizei track_left, - GLsizei track_top, - GLsizei track_width, - GLsizei track_height, + int32_t track_left, + int32_t track_top, + int32_t track_width, + int32_t track_height, float handle_start, float handle_size, bool is_horizontal) { // handle_start and handle_size are fractions of the track length (0..1) // For horizontal: handle moves left-to-right; For vertical: handle moves top-to-bottom // Use lroundf to avoid sub-pixel jitter at the leading edge - GLsizei handle_left, handle_top; - GLsizei handle_w, handle_h; + int32_t handle_left, handle_top; + int32_t handle_w, handle_h; if (is_horizontal) { - GLsizei handle_start_px = (GLsizei)lroundf(handle_start * track_width); - GLsizei handle_end_px = (GLsizei)lroundf((handle_start + handle_size) * track_width); - GLsizei handle_w_px = handle_end_px - handle_start_px; + int32_t handle_start_px = (int32_t)lroundf(handle_start * track_width); + int32_t handle_end_px = (int32_t)lroundf((handle_start + handle_size) * track_width); + int32_t handle_w_px = handle_end_px - handle_start_px; if (handle_w_px < 1) handle_w_px = 1; handle_left = track_left + handle_start_px; handle_top = track_top; handle_w = handle_w_px; handle_h = track_height; } else { - GLsizei handle_start_px = (GLsizei)lroundf(handle_start * track_height); - GLsizei handle_end_px = (GLsizei)lroundf((handle_start + handle_size) * track_height); - GLsizei handle_h_px = handle_end_px - handle_start_px; + int32_t handle_start_px = (int32_t)lroundf(handle_start * track_height); + int32_t handle_end_px = (int32_t)lroundf((handle_start + handle_size) * track_height); + int32_t handle_h_px = handle_end_px - handle_start_px; if (handle_h_px < 1) handle_h_px = 1; handle_left = track_left; handle_top = track_top + handle_start_px; @@ -2011,17 +1900,17 @@ draw_progress_handle( color_vec4(program_uniform_location(ROUNDED_RECT_PROGRAM, "outer_color"), 0, 0.0f); float y = (float)ui->full_framebuffer_height - (float)(handle_top + handle_h); - glUniform4f(program_uniform_location(ROUNDED_RECT_PROGRAM, "rect"), (float)handle_left, y, (float)handle_w, (float)handle_h); + gpu_uniform4f(program_uniform_location(ROUNDED_RECT_PROGRAM, "rect"), (float)handle_left, y, (float)handle_w, (float)handle_h); float thickness = (float)(is_horizontal ? handle_h : handle_w); - glUniform2f(program_uniform_location(ROUNDED_RECT_PROGRAM, "params"), thickness, (float)bar_radius); + gpu_uniform2f(program_uniform_location(ROUNDED_RECT_PROGRAM, "params"), thickness, (float)bar_radius); save_viewport_using_top_left_origin(handle_left, handle_top, handle_w, handle_h, ui->full_framebuffer_height); draw_quad(true, 0); restore_viewport(); } else { // Use GL coordinates within the track viewport, snapped to pixel boundaries - GLsizei track_len = is_horizontal ? track_width : track_height; + int32_t track_len = is_horizontal ? track_width : track_height; float start_snapped = (float)lroundf(handle_start * track_len) / (float)track_len; float end_snapped = (float)lroundf((handle_start + handle_size) * track_len) / (float)track_len; float start_gl = -1.0f + 2.0f * start_snapped; @@ -2031,11 +1920,11 @@ draw_progress_handle( if (is_horizontal) { // edges: left, top, right, bottom save_viewport_using_top_left_origin(track_left, track_top, track_width, track_height, ui->full_framebuffer_height); - glUniform4f(program_uniform_location(TINT_PROGRAM, "edges"), start_gl, 1.f, end_gl, -1.f); + gpu_uniform4f(program_uniform_location(TINT_PROGRAM, "edges"), start_gl, 1.f, end_gl, -1.f); } else { save_viewport_using_top_left_origin(track_left, track_top, track_width, track_height, ui->full_framebuffer_height); // For vertical: start_gl is top in GL coords (inverted y), so bottom_gl = -end_gl, top_gl = -start_gl - glUniform4f(program_uniform_location(TINT_PROGRAM, "edges"), -1.f, -start_gl, 1.f, -end_gl); + gpu_uniform4f(program_uniform_location(TINT_PROGRAM, "edges"), -1.f, -start_gl, 1.f, -end_gl); } draw_quad(true, 0); restore_viewport(); @@ -2054,19 +1943,19 @@ draw_progress_bar(const UIRenderData *ui) { color_type track_color = scrollbar_color(screen, OPT(scrollbar_track_color)); float opacity = OPT(scrollbar_handle_opacity); float track_opacity = OPT(scrollbar_track_hover_opacity); - GLsizei bar_thickness_px = (GLsizei)(OPT(scrollbar_width) * ui->cell_width); - GLsizei gap_px = (GLsizei)(OPT(scrollbar_gap) * ui->cell_width); + int32_t bar_thickness_px = (int32_t)(OPT(scrollbar_width) * ui->cell_width); + int32_t gap_px = (int32_t)(OPT(scrollbar_gap) * ui->cell_width); unsigned bar_radius = (unsigned)(OPT(scrollbar_radius) * ui->cell_width); if (bar_thickness_px < 1) return; // Calculate window boundaries including padding - GLsizei window_left_edge = ui->screen_left - (GLsizei)window->render_data.geometry.spaces.left; - GLsizei window_top_edge = ui->screen_top - (GLsizei)window->render_data.geometry.spaces.top; - GLsizei window_width = ui->screen_width + (GLsizei)(window->render_data.geometry.spaces.left + window->render_data.geometry.spaces.right); - GLsizei window_height = ui->screen_height + (GLsizei)(window->render_data.geometry.spaces.top + window->render_data.geometry.spaces.bottom); + int32_t window_left_edge = ui->screen_left - (int32_t)window->render_data.geometry.spaces.left; + int32_t window_top_edge = ui->screen_top - (int32_t)window->render_data.geometry.spaces.top; + int32_t window_width = ui->screen_width + (int32_t)(window->render_data.geometry.spaces.left + window->render_data.geometry.spaces.right); + int32_t window_height = ui->screen_height + (int32_t)(window->render_data.geometry.spaces.top + window->render_data.geometry.spaces.bottom); // Position the track depending on the chosen edge - GLsizei track_left, track_top, track_width, track_height; + int32_t track_left, track_top, track_width, track_height; switch (pos) { case PROGRESS_BAR_BOTTOM: track_left = window_left_edge + gap_px; @@ -2112,7 +2001,7 @@ draw_progress_bar(const UIRenderData *ui) { if (track_opacity > 0) { bind_program(TINT_PROGRAM); set_color_uniform_with_opacity(track_color, track_opacity); - glUniform4f(program_uniform_location(TINT_PROGRAM, "edges"), -1.f, 1.f, 1.f, -1.f); + gpu_uniform4f(program_uniform_location(TINT_PROGRAM, "edges"), -1.f, 1.f, 1.f, -1.f); draw_quad(true, 0); } restore_viewport(); @@ -2211,10 +2100,10 @@ call_cell_program(int program, const UIRenderData *ui, ssize_t vao_idx, bool for CELL_BUFFERS; bind_vao_uniform_buffer(vao_idx, uniform_buffer, CELL_RENDER_DATA_BINDING_POINT); bind_vao_uniform_buffer(vao_idx, color_table_buffer, COLOR_TABLE_BINDING_POINT); - glUniform1ui(program_uniform_location(program, "draw_bg_bitfield"), draw_bg_bitfield); - if (for_final_output) glEnable(GL_FRAMEBUFFER_SRGB); + gpu_uniform1ui(program_uniform_location(program, "draw_bg_bitfield"), draw_bg_bitfield); + if (for_final_output) gpu_set_srgb_output(true); draw_quad(!for_final_output, render_lines_for_screen(ui->screen) * ui->screen->columns); - if (for_final_output) glDisable(GL_FRAMEBUFFER_SRGB); + if (for_final_output) gpu_set_srgb_output(false); } static void @@ -2229,34 +2118,27 @@ configure_cell_vao_attributes(ssize_t vao_idx, unsigned int base_cell, unsigned // layout after padding draws (base_cell=0, cell_step=1). The VAO must be // bound before calling this. CELL_BUFFERS; - const GLsizei cell_stride = (GLsizei)(cell_step * sizeof(GPUCell)); - const uintptr_t cell_base = (uintptr_t)base_cell * sizeof(GPUCell); + const uint32_t cell_stride = (uint32_t)(cell_step * sizeof(GPUCell)); + const size_t cell_base = (size_t)base_cell * sizeof(GPUCell); set_vao_attribute( vao_idx, cell_data_buffer, program_attribute_location(CELL_PROGRAM, "sprite_idx"), 2, - GL_UNSIGNED_INT, + GPU_ATTRIB_U32, cell_stride, - (void *)(cell_base + offsetof(GPUCell, sprite_idx)), + cell_base + offsetof(GPUCell, sprite_idx), 1); set_vao_attribute( - vao_idx, - cell_data_buffer, - program_attribute_location(CELL_PROGRAM, "colors"), - 3, - GL_UNSIGNED_INT, - cell_stride, - (void *)(cell_base + offsetof(GPUCell, fg)), - 1); + vao_idx, cell_data_buffer, program_attribute_location(CELL_PROGRAM, "colors"), 3, GPU_ATTRIB_U32, cell_stride, cell_base + offsetof(GPUCell, fg), 1); set_vao_attribute( vao_idx, selection_buffer, program_attribute_location(CELL_PROGRAM, "is_selected"), 1, - GL_UNSIGNED_BYTE, - (GLsizei)(cell_step * sizeof(GLubyte)), - (void *)((uintptr_t)base_cell * sizeof(GLubyte)), + GPU_ATTRIB_U8, + (uint32_t)(cell_step * sizeof(uint8_t)), + (size_t)base_cell * sizeof(uint8_t), 1); } @@ -2271,21 +2153,13 @@ configure_padding_vao_attributes(ssize_t vao_idx) { padding_cell_data_buffer, program_attribute_location(CELL_PROGRAM, "sprite_idx"), 2, - GL_UNSIGNED_INT, + GPU_ATTRIB_U32, sizeof(GPUCell), - (void *)offsetof(GPUCell, sprite_idx), + offsetof(GPUCell, sprite_idx), 1); set_vao_attribute( - vao_idx, - padding_cell_data_buffer, - program_attribute_location(CELL_PROGRAM, "colors"), - 3, - GL_UNSIGNED_INT, - sizeof(GPUCell), - (void *)offsetof(GPUCell, fg), - 1); - set_vao_attribute( - vao_idx, padding_selection_buffer, program_attribute_location(CELL_PROGRAM, "is_selected"), 1, GL_UNSIGNED_BYTE, sizeof(GLubyte), NULL, 1); + vao_idx, padding_cell_data_buffer, program_attribute_location(CELL_PROGRAM, "colors"), 3, GPU_ATTRIB_U32, sizeof(GPUCell), offsetof(GPUCell, fg), 1); + set_vao_attribute(vao_idx, padding_selection_buffer, program_attribute_location(CELL_PROGRAM, "is_selected"), 1, GPU_ATTRIB_U8, sizeof(uint8_t), 0, 1); } static void @@ -2319,7 +2193,7 @@ draw_window_padding(const UIRenderData *ui, unsigned int cl, unsigned int ct, un CELL_BUFFERS; bind_vao_uniform_buffer(vao_idx, uniform_buffer, CELL_RENDER_DATA_BINDING_POINT); bind_vao_uniform_buffer(vao_idx, color_table_buffer, COLOR_TABLE_BINDING_POINT); - if (for_final_output) glEnable(GL_FRAMEBUFFER_SRGB); + if (for_final_output) gpu_set_srgb_output(true); // Point instanced attributes at the padding-specific buffers once for both draws. configure_padding_vao_attributes(vao_idx); @@ -2330,42 +2204,42 @@ draw_window_padding(const UIRenderData *ui, unsigned int cl, unsigned int ct, un // Cell data is packed contiguously via GPU-side copies (no CPU round-trip). if (ct || cb) { const unsigned int nH = (ct ? 1u : 0u) + (cb ? 1u : 0u); - alloc_vao_buffer(vao_idx, (GLsizeiptr)(sizeof(GPUCell) * nH * columns), padding_cell_data_buffer, GL_DYNAMIC_DRAW); - alloc_vao_buffer(vao_idx, (GLsizeiptr)(sizeof(GLubyte) * nH * columns), padding_selection_buffer, GL_DYNAMIC_DRAW); + alloc_vao_buffer(vao_idx, (size_t)(sizeof(GPUCell) * nH * columns), padding_cell_data_buffer, GPU_UPDATE_OFTEN); + alloc_vao_buffer(vao_idx, (size_t)(sizeof(uint8_t) * nH * columns), padding_selection_buffer, GPU_UPDATE_OFTEN); unsigned int sidx = 0u; if (ct) { copy_vao_buffer_region( vao_idx, cell_data_buffer, - (GLintptr)(sizeof(GPUCell) * top_row * columns), + (size_t)(sizeof(GPUCell) * top_row * columns), padding_cell_data_buffer, - (GLintptr)(sizeof(GPUCell) * sidx * columns), - (GLsizeiptr)(columns * sizeof(GPUCell))); + (size_t)(sizeof(GPUCell) * sidx * columns), + (size_t)(columns * sizeof(GPUCell))); copy_vao_buffer_region( vao_idx, selection_buffer, - (GLintptr)(sizeof(GLubyte) * top_row * columns), + (size_t)(sizeof(uint8_t) * top_row * columns), padding_selection_buffer, - (GLintptr)(sizeof(GLubyte) * sidx * columns), - (GLsizeiptr)(columns * sizeof(GLubyte))); + (size_t)(sizeof(uint8_t) * sidx * columns), + (size_t)(columns * sizeof(uint8_t))); sidx++; } if (cb) { copy_vao_buffer_region( vao_idx, cell_data_buffer, - (GLintptr)(sizeof(GPUCell) * bottom_row * columns), + (size_t)(sizeof(GPUCell) * bottom_row * columns), padding_cell_data_buffer, - (GLintptr)(sizeof(GPUCell) * sidx * columns), - (GLsizeiptr)(sizeof(GPUCell) * columns)); + (size_t)(sizeof(GPUCell) * sidx * columns), + (size_t)(sizeof(GPUCell) * columns)); copy_vao_buffer_region( vao_idx, selection_buffer, - (GLintptr)(sizeof(GLubyte) * bottom_row * columns), + (size_t)(sizeof(uint8_t) * bottom_row * columns), padding_selection_buffer, - (GLintptr)(sizeof(GLubyte) * sidx * columns), - (GLsizeiptr)(columns * sizeof(GLubyte))); + (size_t)(sizeof(uint8_t) * sidx * columns), + (size_t)(columns * sizeof(uint8_t))); } // Strip-0 is top (or bottom when only bottom exists); strip-1 is bottom. @@ -2373,16 +2247,16 @@ draw_window_padding(const UIRenderData *ui, unsigned int cl, unsigned int ct, un // the shader lerp is a no-op for all instances (strip_f is always 0.0). const unsigned int base0 = (ct ? top_row : bottom_row) * columns; const unsigned int base1 = bottom_row * columns; - glUniform1ui(PL(is_horizontal), 1u); - glUniform1ui(PL(along_count), columns); - glUniform1ui(PL(instance_step), 1u); - glUniform1ui(PL(base_instance), base0); - glUniform1ui(PL(base_instance2), base1); - glUniform2f(PL(across), ct ? NY(T - ct) : NY(B), ct ? NY(T) : NY(B + cb)); - glUniform2f(PL(across2), NY(B), NY(B + cb)); - glUniform1f(PL(along_start), NX(fL)); - glUniform1f(PL(along_step), dx); - glUniform2f(PL(along_clamp), NX(fL), NX(R)); + gpu_uniform1ui(PL(is_horizontal), 1u); + gpu_uniform1ui(PL(along_count), columns); + gpu_uniform1ui(PL(instance_step), 1u); + gpu_uniform1ui(PL(base_instance), base0); + gpu_uniform1ui(PL(base_instance2), base1); + gpu_uniform2f(PL(across), ct ? NY(T - ct) : NY(B), ct ? NY(T) : NY(B + cb)); + gpu_uniform2f(PL(across2), NY(B), NY(B + cb)); + gpu_uniform1f(PL(along_start), NX(fL)); + gpu_uniform1f(PL(along_step), dx); + gpu_uniform2f(PL(along_clamp), NX(fL), NX(R)); draw_quad(!for_final_output, nH * columns); } @@ -2393,7 +2267,7 @@ draw_window_padding(const UIRenderData *ui, unsigned int cl, unsigned int ct, un const unsigned int nV = (cl ? 1u : 0u) + (cr ? 1u : 0u); // VLA sizes: lines is bounded by the window height / cell height (~<500). GPUCell gathered_cells[2 * lines]; - GLubyte gathered_sel[2 * lines]; + uint8_t gathered_sel[2 * lines]; const unsigned int strip0_col = cl ? 0u : (columns - 1u); const unsigned int strip1_col = columns - 1u; @@ -2405,38 +2279,38 @@ draw_window_padding(const UIRenderData *ui, unsigned int cl, unsigned int ct, un } unmap_vao_buffer(vao_idx, cell_data_buffer); - const GLubyte *sel = (const GLubyte *)map_vao_buffer_for_reading(vao_idx, selection_buffer); + const uint8_t *sel = (const uint8_t *)map_vao_buffer_for_reading(vao_idx, selection_buffer); for (unsigned int i = 0; i < lines; i++) { gathered_sel[i] = sel[(top_row + i) * columns + strip0_col]; if (nV == 2u) gathered_sel[lines + i] = sel[(top_row + i) * columns + strip1_col]; } unmap_vao_buffer(vao_idx, selection_buffer); - void *dst = alloc_and_map_vao_buffer(vao_idx, (GLsizeiptr)(sizeof(GPUCell) * nV * lines), padding_cell_data_buffer); + void *dst = alloc_and_map_vao_buffer(vao_idx, (size_t)(sizeof(GPUCell) * nV * lines), padding_cell_data_buffer); memcpy(dst, gathered_cells, sizeof(GPUCell) * nV * lines); unmap_vao_buffer(vao_idx, padding_cell_data_buffer); - dst = alloc_and_map_vao_buffer(vao_idx, (GLsizeiptr)(sizeof(GLubyte) * nV * lines), padding_selection_buffer); - memcpy(dst, gathered_sel, sizeof(GLubyte) * nV * lines); + dst = alloc_and_map_vao_buffer(vao_idx, (size_t)(sizeof(uint8_t) * nV * lines), padding_selection_buffer); + memcpy(dst, gathered_sel, sizeof(uint8_t) * nV * lines); unmap_vao_buffer(vao_idx, padding_selection_buffer); const unsigned int base0 = top_row * columns + (cl ? 0u : (columns - 1u)); const unsigned int base1 = top_row * columns + (columns - 1u); - glUniform1ui(PL(is_horizontal), 0u); - glUniform1ui(PL(along_count), lines); - glUniform1ui(PL(instance_step), columns); - glUniform1ui(PL(base_instance), base0); - glUniform1ui(PL(base_instance2), base1); - glUniform2f(PL(across), cl ? NX(fL - cl) : NX(R), cl ? NX(fL) : NX(R + cr)); - glUniform2f(PL(across2), NX(R), NX(R + cr)); - glUniform1f(PL(along_start), NY(T)); - glUniform1f(PL(along_step), -dy); - glUniform2f(PL(along_clamp), NY(T - ct), NY(B + cb)); + gpu_uniform1ui(PL(is_horizontal), 0u); + gpu_uniform1ui(PL(along_count), lines); + gpu_uniform1ui(PL(instance_step), columns); + gpu_uniform1ui(PL(base_instance), base0); + gpu_uniform1ui(PL(base_instance2), base1); + gpu_uniform2f(PL(across), cl ? NX(fL - cl) : NX(R), cl ? NX(fL) : NX(R + cr)); + gpu_uniform2f(PL(across2), NX(R), NX(R + cr)); + gpu_uniform1f(PL(along_start), NY(T)); + gpu_uniform1f(PL(along_step), -dy); + gpu_uniform2f(PL(along_clamp), NY(T - ct), NY(B + cb)); draw_quad(!for_final_output, nV * lines); } #undef PL - if (for_final_output) glDisable(GL_FRAMEBUFFER_SRGB); + if (for_final_output) gpu_set_srgb_output(false); // Restore the canonical cell attribute layout so subsequent cell rendering is unaffected. configure_cell_vao_attributes(vao_idx, 0u, 1u); unbind_program(); @@ -2448,7 +2322,7 @@ static void draw_tint(const UIRenderData *ui) { bind_program(TINT_PROGRAM); color_vec4_premult(program_uniform_location(TINT_PROGRAM, "tint_color"), ui->background_color, OPT(background_tint)); - glUniform4f(program_uniform_location(TINT_PROGRAM, "edges"), -1, 1, 1, -1); + gpu_uniform4f(program_uniform_location(TINT_PROGRAM, "edges"), -1, 1, 1, -1); draw_quad(true, 0); } @@ -2463,7 +2337,7 @@ program_for_image(const ImageRenderData *rd) { } static void -draw_image_layer(const UIRenderData *ui, ssize_t vao_idx, GLuint start, GLuint count) { +draw_image_layer(const UIRenderData *ui, ssize_t vao_idx, uint32_t start, uint32_t count) { if (!ui->grd.num_of_indexed_refs) { draw_graphics(GRAPHICS_PROGRAM, ui->grd.images, start, count, ui->inactive_text_alpha); return; @@ -2472,9 +2346,9 @@ draw_image_layer(const UIRenderData *ui, ssize_t vao_idx, GLuint start, GLuint c // The color table may not be bound yet, for example, when the window has a background image bind_vao_uniform_buffer(vao_idx, color_table_buffer, COLOR_TABLE_BINDING_POINT); const ImageRenderData *data = ui->grd.images; - for (GLuint run_start = start, end = start + count; run_start < end;) { + for (uint32_t run_start = start, end = start + count; run_start < end;) { const int program = program_for_image(data + run_start); - GLuint run_end = run_start + 1; + uint32_t run_end = run_start + 1; while (run_end < end && program_for_image(data + run_end) == program) run_end++; draw_graphics(program, ui->grd.images, run_start, run_end - run_start, ui->inactive_text_alpha); run_start = run_end; @@ -2509,15 +2383,14 @@ blank_canvas(float background_opacity, color_type color_in_srgb, bool for_final_ if (for_final_output) { // we need to write pre-multiplied sRGB color to framebuffer #define C(shift) ((((color_in_srgb >> shift) & 0xFF) / 255.f) * background_opacity) - glClearColor(C(16), C(8), C(0), background_opacity); + gpu_clear(C(16), C(8), C(0), background_opacity); #undef C } else { // we need to write pre-multiplied linear color to framebuffer #define C(shift) srgb_color((color_in_srgb >> shift) & 0xFF) * background_opacity - glClearColor(C(16), C(8), C(0), background_opacity); + gpu_clear(C(16), C(8), C(0), background_opacity); #undef C } - glClear(GL_COLOR_BUFFER_BIT); } bool @@ -2611,7 +2484,7 @@ draw_cells( // Borders {{{ static void -populate_border_colors(GLuint colors[9], color_type active_window_bg, unsigned int num_visible_windows, bool all_windows_have_same_bg, const OSWindow *w) { +populate_border_colors(uint32_t colors[9], color_type active_window_bg, unsigned int num_visible_windows, bool all_windows_have_same_bg, const OSWindow *w) { colors[0] = (num_visible_windows > 1 && !all_windows_have_same_bg) ? OPT(background) : active_window_bg; colors[1] = OPT(active_border_color); colors[2] = OPT(inactive_border_color); @@ -2627,22 +2500,22 @@ ssize_t create_border_vao(void) { ssize_t vao_idx = create_vao(); - add_buffer_to_vao(vao_idx, GL_ARRAY_BUFFER); + add_buffer_to_vao(vao_idx, GPU_BUFFER_VERTEX); add_attribute_to_vao( vao_idx, program_attribute_location(BORDERS_PROGRAM, "rect"), /*size=*/4, - /*dtype=*/GL_FLOAT, + /*dtype=*/GPU_ATTRIB_F32, /*stride=*/sizeof(BorderRect), - /*offset=*/(void *)offsetof(BorderRect, left), + /*offset=*/offsetof(BorderRect, left), /*divisor=*/1); add_attribute_to_vao( vao_idx, program_attribute_location(BORDERS_PROGRAM, "rect_color"), /*size=*/1, - /*dtype=*/GL_UNSIGNED_INT, + /*dtype=*/GPU_ATTRIB_U32, /*stride=*/sizeof(BorderRect), - /*offset=*/(void *)(offsetof(BorderRect, color)), + /*offset=*/offsetof(BorderRect, color), /*divisor=*/1); return vao_idx; @@ -2670,17 +2543,17 @@ draw_borders( if (borders_buf_address) memcpy(borders_buf_address, rect_buf, sz); unmap_vao_buffer(vao_idx, 0); } - GLuint colors[9]; + uint32_t colors[9]; populate_border_colors(colors, active_window_bg, num_visible_windows, all_windows_have_same_bg, w); void *colors_buf = map_vao_buffer_for_write_only(shader_globals_vao_idx, BORDER_COLORS_GLOBAL_BUFFER, 0, program_uniform_block(BORDERS_PROGRAM, "Colors").size); const ArrayInformation border_colors_array = program_uniform_array(BORDERS_PROGRAM, "colors"); write_uint_array_to_ubo(colors_buf, colors, arraysz(colors), &border_colors_array); unmap_vao_buffer(shader_globals_vao_idx, BORDER_COLORS_GLOBAL_BUFFER); - glUniform1f(program_uniform_location(BORDERS_PROGRAM, "background_opacity"), background_opacity); - if (!w->needs_layers) glEnable(GL_FRAMEBUFFER_SRGB); + gpu_uniform1f(program_uniform_location(BORDERS_PROGRAM, "background_opacity"), background_opacity); + if (!w->needs_layers) gpu_set_srgb_output(true); draw_quad(has_background_image, num_border_rects); - if (!w->needs_layers) glDisable(GL_FRAMEBUFFER_SRGB); + if (!w->needs_layers) gpu_set_srgb_output(false); unbind_program(); unbind_vertex_array(); } @@ -2688,7 +2561,7 @@ draw_borders( void draw_rounded_borders(BorderRects *br, color_type active_window_bg, unsigned int num_visible_windows, bool all_windows_have_same_bg, OSWindow *w) { if (!br->num_rounded_rects) return; - GLuint colors[9]; + uint32_t colors[9]; populate_border_colors(colors, active_window_bg, num_visible_windows, all_windows_have_same_bg, w); // The corner regions between the rounded outline and its bounding rect // must be painted every frame: when not rendering in layers the @@ -2697,7 +2570,7 @@ draw_rounded_borders(BorderRects *br, color_type active_window_bg, unsigned int // uses for non-border rects, so corners match the surrounding gaps. float corner_bg_alpha = has_bgimage(w) ? OPT(background_tint) * OPT(background_tint_gaps) : effective_os_window_alpha(w); bind_vertex_array(br->vao_idx); - if (!w->needs_layers) glEnable(GL_FRAMEBUFFER_SRGB); + if (!w->needs_layers) gpu_set_srgb_output(true); for (unsigned i = 0; i < br->num_border_rects; i++) { const BorderRect *r = br->rect_buf + i; if (!r->radius || !r->thickness) continue; @@ -2707,7 +2580,7 @@ draw_rounded_borders(BorderRects *br, color_type active_window_bg, unsigned int color_type color = color_index == 3 ? r->color >> 8 : colors[MIN(color_index, 8u)]; draw_rounded_rect(rect, w->viewport_height, (float)r->thickness, radius, color, 0, 0.f, colors[0], corner_bg_alpha); } - if (!w->needs_layers) glDisable(GL_FRAMEBUFFER_SRGB); + if (!w->needs_layers) gpu_set_srgb_output(false); unbind_program(); // Deliberately leave the VAO bound: this runs after all cell drawing and // subsequent draw_quad() calls (e.g. the fullscreen blit in @@ -2721,11 +2594,11 @@ void draw_cursor_trail(CursorTrail *trail, Window *active_window) { bind_program(TRAIL_PROGRAM); - glUniform4fv(program_uniform_location(TRAIL_PROGRAM, "x_coords"), 1, trail->corner_x); - glUniform4fv(program_uniform_location(TRAIL_PROGRAM, "y_coords"), 1, trail->corner_y); + gpu_set_uniform_floats(program_uniform_location(TRAIL_PROGRAM, "x_coords"), 4, 1, trail->corner_x); + gpu_set_uniform_floats(program_uniform_location(TRAIL_PROGRAM, "y_coords"), 4, 1, trail->corner_y); - glUniform2fv(program_uniform_location(TRAIL_PROGRAM, "cursor_edge_x"), 1, trail->cursor_edge_x); - glUniform2fv(program_uniform_location(TRAIL_PROGRAM, "cursor_edge_y"), 1, trail->cursor_edge_y); + gpu_set_uniform_floats(program_uniform_location(TRAIL_PROGRAM, "cursor_edge_x"), 2, 1, trail->cursor_edge_x); + gpu_set_uniform_floats(program_uniform_location(TRAIL_PROGRAM, "cursor_edge_y"), 2, 1, trail->cursor_edge_y); color_type trail_color = OPT(cursor_trail_color); if (trail_color == 0) { // 0 means "none" was specified @@ -2733,7 +2606,7 @@ draw_cursor_trail(CursorTrail *trail, Window *active_window) { } color_vec3(program_uniform_location(TRAIL_PROGRAM, "trail_color"), trail_color); - glUniform1f(program_uniform_location(TRAIL_PROGRAM, "trail_opacity"), trail->opacity); + gpu_uniform1f(program_uniform_location(TRAIL_PROGRAM, "trail_opacity"), trail->opacity); draw_quad(true, 0); unbind_program(); @@ -2756,10 +2629,10 @@ draw_bg_image(OSWindow *os_window, Tab *tab) { .bgcolor = OPT(background), .opacity = effective_os_window_alpha(os_window), }; - GLfloat iwidth = bg->width, iheight = bg->height; - GLfloat vwidth = s.os_window.width, vheight = s.os_window.height; + float iwidth = bg->width, iheight = bg->height; + float vwidth = s.os_window.width, vheight = s.os_window.height; if (CENTER_SCALED == layout) { - GLfloat ifrac = iwidth / iheight; + float ifrac = iwidth / iheight; if (ifrac > (vwidth / vheight)) { iheight = vheight; iwidth = iheight * ifrac; @@ -2768,9 +2641,9 @@ draw_bg_image(OSWindow *os_window, Tab *tab) { iheight = iwidth / ifrac; } } - GLfloat tiled = 0.f; + float tiled = 0.f; ; - GLfloat left = -1.0, top = 1.0, right = 1.0, bottom = -1.0; + float left = -1.0, top = 1.0, right = 1.0, bottom = -1.0; switch (layout) { case TILING: case MIRRORED: @@ -2778,8 +2651,8 @@ draw_bg_image(OSWindow *os_window, Tab *tab) { case SCALED: break; case CENTER_CLAMPED: case CENTER_SCALED: { - GLfloat wfrac = (vwidth - iwidth) / vwidth; - GLfloat hfrac = (vheight - iheight) / vheight; + float wfrac = (vwidth - iwidth) / vwidth; + float hfrac = (vheight - iheight) / vheight; left += wfrac; right -= wfrac; top -= hfrac; @@ -2789,13 +2662,12 @@ draw_bg_image(OSWindow *os_window, Tab *tab) { bind_program(BGIMAGE_PROGRAM); // altough we dont use this VO we need to ensure *some* VAO is bound at this point. bind_vertex_array(tab->border_rects.vao_idx); - glUniform4f(program_uniform_location(BGIMAGE_PROGRAM, "sizes"), vwidth, vheight, iwidth, iheight); - glUniform1f(program_uniform_location(BGIMAGE_PROGRAM, "tiled"), tiled); - glUniform4f(program_uniform_location(BGIMAGE_PROGRAM, "positions"), left, top, right, bottom); - glUniform1i(program_uniform_location(BGIMAGE_PROGRAM, "image"), GRAPHICS_UNIT); + gpu_uniform4f(program_uniform_location(BGIMAGE_PROGRAM, "sizes"), vwidth, vheight, iwidth, iheight); + gpu_uniform1f(program_uniform_location(BGIMAGE_PROGRAM, "tiled"), tiled); + gpu_uniform4f(program_uniform_location(BGIMAGE_PROGRAM, "positions"), left, top, right, bottom); + gpu_uniform1i(program_uniform_location(BGIMAGE_PROGRAM, "image"), GRAPHICS_UNIT); color_vec4(program_uniform_location(BGIMAGE_PROGRAM, "background"), s.bgcolor, s.opacity); - glActiveTexture(GL_TEXTURE0 + GRAPHICS_UNIT); - glBindTexture(GL_TEXTURE_2D, bg->texture_id); + gpu_bind_texture(GRAPHICS_UNIT, bg->texture_id); draw_quad(false, 0); unbind_program(); } @@ -2813,7 +2685,7 @@ draw_centered_alpha_mask(size_t screen_width, size_t screen_height, size_t width ImageRenderData *data = load_alpha_mask_texture(width, height, canvas); gpu_data_for_centered_image(data, screen_width, screen_height, width, height); bind_program(GRAPHICS_ALPHA_MASK_PROGRAM); - glUniform1i(program_uniform_location(GRAPHICS_ALPHA_MASK_PROGRAM, "image"), GRAPHICS_UNIT); + gpu_uniform1i(program_uniform_location(GRAPHICS_ALPHA_MASK_PROGRAM, "image"), GRAPHICS_UNIT); color_vec3(program_uniform_location(GRAPHICS_ALPHA_MASK_PROGRAM, "amask_fg"), OPT(foreground)); color_vec4_premult(program_uniform_location(GRAPHICS_ALPHA_MASK_PROGRAM, "amask_bg_premult"), OPT(background), background_opacity); draw_graphics(GRAPHICS_ALPHA_MASK_PROGRAM, data, 0, 1, 1.0); @@ -2847,6 +2719,14 @@ blank_os_window(OSWindow *osw) { blank_canvas(effective_os_window_alpha(osw), color, true); } +// (Re)create a render target that draws into texture, freeing any existing one +static void +create_render_target_for(gpu_render_target_t *fb, gpu_texture_t texture) { + if (*fb) free_framebuffer(fb); + *fb = gpu_render_target_create(texture); + if (!*fb) fatal("Failed to create a GPU render target with error: %s", gpu_last_error()); +} + static void start_os_window_rendering(OSWindow *os_window, Tab *tab) { // note that during live resize rendering is done in layers @@ -2870,10 +2750,9 @@ start_os_window_rendering(OSWindow *os_window, Tab *tab) { global_state.layers_render_texture.texture_generation++; } // Create per-window framebuffer if needed and attach the global texture to it - if (!os_window->indirect_output.framebuffer_id) glGenFramebuffers(1, &os_window->indirect_output.framebuffer_id); - if (os_window->indirect_output.attached_texture_generation != global_state.layers_render_texture.texture_generation) { - bind_framebuffer_for_output(os_window->indirect_output.framebuffer_id); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, global_state.layers_render_texture.texture_id, 0); + if (!os_window->indirect_output.framebuffer_id || + os_window->indirect_output.attached_texture_generation != global_state.layers_render_texture.texture_generation) { + create_render_target_for(&os_window->indirect_output.framebuffer_id, global_state.layers_render_texture.texture_id); os_window->indirect_output.attached_texture_generation = global_state.layers_render_texture.texture_generation; } if (custom_shaders.end.num_groups > 1) { @@ -2887,10 +2766,7 @@ start_os_window_rendering(OSWindow *os_window, Tab *tab) { } // Create/re-attach per-window extra FBO when generation changes if (os_window->indirect_output.extra_fbo_generation != global_state.layers_render_texture.texture_generation) { - if (os_window->indirect_output.extra_fbo_id) free_framebuffer(&os_window->indirect_output.extra_fbo_id); - glGenFramebuffers(1, &os_window->indirect_output.extra_fbo_id); - bind_framebuffer_for_output(os_window->indirect_output.extra_fbo_id); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, global_state.layers_render_texture.extra_texture_id, 0); + create_render_target_for(&os_window->indirect_output.extra_fbo_id, global_state.layers_render_texture.extra_texture_id); os_window->indirect_output.extra_fbo_generation = global_state.layers_render_texture.texture_generation; } } @@ -2904,10 +2780,7 @@ start_os_window_rendering(OSWindow *os_window, Tab *tab) { &global_state.layers_render_texture.texture_a_fbo_id); } if (os_window->indirect_output.fbo_a_generation != global_state.layers_render_texture.texture_generation) { - if (os_window->indirect_output.fbo_a_id) free_framebuffer(&os_window->indirect_output.fbo_a_id); - glGenFramebuffers(1, &os_window->indirect_output.fbo_a_id); - bind_framebuffer_for_output(os_window->indirect_output.fbo_a_id); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, global_state.layers_render_texture.texture_a_id, 0); + create_render_target_for(&os_window->indirect_output.fbo_a_id, global_state.layers_render_texture.texture_a_id); os_window->indirect_output.fbo_a_generation = global_state.layers_render_texture.texture_generation; } } else { @@ -2923,10 +2796,7 @@ start_os_window_rendering(OSWindow *os_window, Tab *tab) { &global_state.layers_render_texture.texture_b_fbo_id); } if (os_window->indirect_output.fbo_b_generation != global_state.layers_render_texture.texture_generation) { - if (os_window->indirect_output.fbo_b_id) free_framebuffer(&os_window->indirect_output.fbo_b_id); - glGenFramebuffers(1, &os_window->indirect_output.fbo_b_id); - bind_framebuffer_for_output(os_window->indirect_output.fbo_b_id); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, global_state.layers_render_texture.texture_b_id, 0); + create_render_target_for(&os_window->indirect_output.fbo_b_id, global_state.layers_render_texture.texture_b_id); os_window->indirect_output.fbo_b_generation = global_state.layers_render_texture.texture_generation; } } else { @@ -3016,7 +2886,7 @@ map_pointer_position(const OSWindow *os_window, double *x, double *y) { // pointer map can depend only on the pipeline, the viewport size and which // groups are active, so this is done only when those change. static void -update_pointer_map(OSWindow *os_window, GLint group_loc) { +update_pointer_map(OSWindow *os_window, int32_t group_loc) { const uint32_t groups = active_pointer_map_groups(os_window); if (os_window->pointer_map.pipeline_generation == custom_shaders.generation && os_window->pointer_map.groups == groups && (os_window->pointer_map.data || !groups)) { @@ -3034,19 +2904,16 @@ update_pointer_map(OSWindow *os_window, GLint group_loc) { setup_texture_as_render_target(POINTER_MAP_SIZE, POINTER_MAP_SIZE, &pointer_map_target.texture_id, &pointer_map_target.framebuffer_id); // The pointer map does not sample any textures, but every sampler must be bound to a valid one static const int units[] = {GRAPHICS_UNIT, CUSTOM_END_TEXTURE_A_UNIT, CUSTOM_END_TEXTURE_B_UNIT, CUSTOM_END_TEXTURE_PERSIST_UNIT}; - for (size_t i = 0; i < arraysz(units); i++) { - glActiveTexture(GL_TEXTURE0 + units[i]); - glBindTexture(GL_TEXTURE_2D, global_state.layers_render_texture.texture_id); - } + for (size_t i = 0; i < arraysz(units); i++) { gpu_bind_texture(units[i], global_state.layers_render_texture.texture_id); } bind_framebuffer_for_output(pointer_map_target.framebuffer_id); - glViewport(0, 0, POINTER_MAP_SIZE, POINTER_MAP_SIZE); - glUniform1i(group_loc, -1); + gpu_set_viewport(0, 0, POINTER_MAP_SIZE, POINTER_MAP_SIZE); + gpu_uniform1i(group_loc, -1); // Absent when no group with a pointer_map() is turned on and off by events - GLint active_groups_loc = try_program_uniform_location(CUSTOM_END_PROGRAM, "active_groups"); - if (active_groups_loc >= 0) glUniform1ui(active_groups_loc, groups); + int32_t active_groups_loc = try_program_uniform_location(CUSTOM_END_PROGRAM, "active_groups"); + if (active_groups_loc >= 0) gpu_uniform1ui(active_groups_loc, groups); draw_quad(false, 0); static uint8_t pixels[POINTER_MAP_SIZE * POINTER_MAP_SIZE * 4]; - glReadPixels(0, 0, POINTER_MAP_SIZE, POINTER_MAP_SIZE, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + gpu_read_pixels(0, 0, POINTER_MAP_SIZE, POINTER_MAP_SIZE, pixels); // See encode_pointer_map() in pipeline.slang for (size_t i = 0; i < POINTER_MAP_SIZE * POINTER_MAP_SIZE; i++) { const uint8_t *p = pixels + 4 * i; @@ -3307,23 +3174,23 @@ run_custom_end_shader(OSWindow *os_window, float sx, float sy, monotonic_t now) // A custom shader need not reference any of these, in which case the driver // drops them and glUniform*() on the resulting -1 location is a no-op. - GLint group_loc = try_program_uniform_location(CUSTOM_END_PROGRAM, "group"); - GLint viewport_loc = try_program_uniform_location(CUSTOM_END_PROGRAM, "viewport"); - GLint anim_progress_loc = try_program_uniform_location(CUSTOM_END_PROGRAM, "animation_progress"); - GLint convert_to_srgb_loc = try_program_uniform_location(CUSTOM_END_PROGRAM, "convert_to_srgb"); + int32_t group_loc = try_program_uniform_location(CUSTOM_END_PROGRAM, "group"); + int32_t viewport_loc = try_program_uniform_location(CUSTOM_END_PROGRAM, "viewport"); + int32_t anim_progress_loc = try_program_uniform_location(CUSTOM_END_PROGRAM, "animation_progress"); + int32_t convert_to_srgb_loc = try_program_uniform_location(CUSTOM_END_PROGRAM, "convert_to_srgb"); if (custom_shaders.end.has_pointer_map && group_loc >= 0) update_pointer_map(os_window, group_loc); const unsigned num_groups = (unsigned)custom_shaders.end.num_groups; const unsigned textures_mask = custom_shaders.end.textures; const int vw = os_window->viewport_width, vh = os_window->viewport_height; // Named texture IDs and their render-target FBOs, indexed by NamedTexture enum value - const GLuint named_tex_ids[4] = { + const gpu_texture_t named_tex_ids[4] = { 0, // DEFAULT — unused global_state.layers_render_texture.texture_a_id, global_state.layers_render_texture.texture_b_id, os_window->persist_texture_id, }; - const GLuint named_tex_fbos[4] = { + const gpu_render_target_t named_tex_fbos[4] = { 0, // DEFAULT — unused os_window->indirect_output.fbo_a_id, os_window->indirect_output.fbo_b_id, @@ -3360,17 +3227,17 @@ run_custom_end_shader(OSWindow *os_window, float sx, float sy, monotonic_t now) // Skip inactive groups. Non-attached, non-animated groups always run; all others require // shader_group_anim[g].active (set by update_custom_shader_animations, including attach logic). if (group_is_animated(cg) && !os_window->shader_group_anim[g].active) continue; - const GLuint backbuffer = backbuffer_is_main ? global_state.layers_render_texture.texture_id : global_state.layers_render_texture.extra_texture_id; + const gpu_texture_t backbuffer = + backbuffer_is_main ? global_state.layers_render_texture.texture_id : global_state.layers_render_texture.extra_texture_id; // Bind backbuffer to the backbuffer texture unit - glActiveTexture(GL_TEXTURE0 + GRAPHICS_UNIT); - glBindTexture(GL_TEXTURE_2D, backbuffer); + gpu_bind_texture(GRAPHICS_UNIT, backbuffer); // Bind each named texture to its own unit. // If the texture is the output for this group, or is not declared in the // pipeline, fall back to backbuffer so the sampler is always valid. for (int t = CUSTOM_SHADER_TEXTURE_A; t <= CUSTOM_SHADER_TEXTURE_PERSIST; t++) { - GLuint tex; + gpu_texture_t tex; if (!is_last && cg->output_texture == (NamedTexture)t) { tex = backbuffer; // can't read from the render target we're writing to } else if (textures_mask & (1u << t)) { @@ -3378,8 +3245,7 @@ run_custom_end_shader(OSWindow *os_window, float sx, float sy, monotonic_t now) } else { tex = backbuffer; // not present — fall back to backbuffer } - glActiveTexture(GL_TEXTURE0 + named_tex_units[t]); - glBindTexture(GL_TEXTURE_2D, tex); + gpu_bind_texture(named_tex_units[t], tex); } // Set the output framebuffer @@ -3400,9 +3266,9 @@ run_custom_end_shader(OSWindow *os_window, float sx, float sy, monotonic_t now) if (is_last) { // Last group always covers the full screen region if (os_window->live_resize.in_progress) { - glViewport(0, os_window->live_resize.height - vh, vw, vh); + gpu_set_viewport(0, os_window->live_resize.height - vh, vw, vh); } else { - glViewport(0, 0, vw, vh); + gpu_set_viewport(0, 0, vw, vh); } vp_x = 0.f; vp_y = 0.f; @@ -3413,21 +3279,21 @@ run_custom_end_shader(OSWindow *os_window, float sx, float sy, monotonic_t now) float sw = cg->viewport_size.w, sh = cg->viewport_size.h; // viewport_pos/size are standard UV (origin at bottom-left, y increasing // upward), which matches GL pixel coords directly — no y-flip needed. - GLint x0 = MAX(0, (GLint)(px * vw)); - GLint y0 = MAX(0, (GLint)(py * vh)); - GLint x1 = MIN(vw, (GLint)((px + sw) * vw)); - GLint y1 = MIN(vh, (GLint)((py + sh) * vh)); - glViewport(x0, y0, MAX(0, x1 - x0), MAX(0, y1 - y0)); + int32_t x0 = MAX(0, (int32_t)(px * vw)); + int32_t y0 = MAX(0, (int32_t)(py * vh)); + int32_t x1 = MIN(vw, (int32_t)((px + sw) * vw)); + int32_t y1 = MIN(vh, (int32_t)((py + sh) * vh)); + gpu_set_viewport(x0, y0, MAX(0, x1 - x0), MAX(0, y1 - y0)); vp_x = px; vp_y = py; vp_w = sw; vp_h = sh; } - glUniform1i(group_loc, (GLint)g); - glUniform4f(viewport_loc, vp_x, vp_y, vp_w, vp_h); - glUniform1f(anim_progress_loc, anim_progress[g]); - glUniform1i(convert_to_srgb_loc, is_last ? 1 : 0); + gpu_uniform1i(group_loc, (int32_t)g); + gpu_uniform4f(viewport_loc, vp_x, vp_y, vp_w, vp_h); + gpu_uniform1f(anim_progress_loc, anim_progress[g]); + gpu_uniform1i(convert_to_srgb_loc, is_last ? 1 : 0); // debug_rendering("Custom shader draw group %u: anim_progress=%.4f viewport=(%.2f,%.2f,%.2f,%.2f)\n", g, anim_progress[g], vp_x, vp_y, vp_w, vp_h); draw_quad(false, 0); } @@ -3451,10 +3317,9 @@ stop_os_window_rendering(OSWindow *os_window, Tab *tab, Window *active_window, m set_framebuffer_to_use_for_output(0); bind_framebuffer_for_output(0); bind_program(BLIT_PROGRAM); - glActiveTexture(GL_TEXTURE0 + GRAPHICS_UNIT); - glBindTexture(GL_TEXTURE_2D, global_state.layers_render_texture.texture_id); - glUniform4f(program_uniform_location(BLIT_PROGRAM, "src_rect"), 0, sy, sx, 0); - glUniform4f(program_uniform_location(BLIT_PROGRAM, "dest_rect"), -1, 1, 1, -1); + gpu_bind_texture(GRAPHICS_UNIT, global_state.layers_render_texture.texture_id); + gpu_uniform4f(program_uniform_location(BLIT_PROGRAM, "src_rect"), 0, sy, sx, 0); + gpu_uniform4f(program_uniform_location(BLIT_PROGRAM, "dest_rect"), -1, 1, 1, -1); restore_viewport(); if (os_window->live_resize.in_progress) save_viewport_using_top_left_origin(0, 0, os_window->viewport_width, os_window->viewport_height, os_window->live_resize.height); @@ -3499,9 +3364,7 @@ take_screenshot_of_rectangular_region(OSWindow *os_window, Region region, unsign if (no_scaling) { *thumb_w = src_width; *thumb_h = src_height; - glPixelStorei(GL_PACK_ALIGNMENT, 1); - glReadPixels((GLint)region.left, (GLint)(vh - region.bottom), (GLsizei)src_width, (GLsizei)src_height, GL_RGBA, GL_UNSIGNED_BYTE, dst_buf); - glPixelStorei(GL_PACK_ALIGNMENT, 4); + gpu_read_pixels((int32_t)region.left, (int32_t)(vh - region.bottom), src_width, src_height, dst_buf); return; } @@ -3512,24 +3375,20 @@ take_screenshot_of_rectangular_region(OSWindow *os_window, Region region, unsign *thumb_h = MIN(src_height, *thumb_h); // Create a texture to hold the current framebuffer content - GLuint src_texture = 0; - glGenTextures(1, &src_texture); - glBindTexture(GL_TEXTURE_2D, src_texture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + const GPUTextureDesc desc = { + .kind = GPU_TEXTURE_2D, .format = GPU_FORMAT_RGBA8, .width = vw, .height = vh, .filter = GPU_FILTER_LINEAR, .wrap = GPU_WRAP_CLAMP_TO_EDGE}; + gpu_texture_t src_texture = create_texture_or_die(&desc, NULL); // Copy the current framebuffer to the texture - glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, vw, vh, 0); + gpu_copy_to_texture(src_texture, 0, 0, vw, vh); // Create a temporary framebuffer for GPU-based scaling - GLuint temp_texture = 0, temp_framebuffer = 0; + gpu_texture_t temp_texture = 0; + gpu_render_target_t temp_framebuffer = 0; setup_texture_as_render_target(*thumb_w, *thumb_h, &temp_texture, &temp_framebuffer); // Save current state - GLint current_framebuffer; - glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, ¤t_framebuffer); + gpu_render_target_t current_framebuffer = gpu_get_render_target(); // Bind our temporary framebuffer for rendering bind_framebuffer_for_output(temp_framebuffer); @@ -3545,28 +3404,25 @@ take_screenshot_of_rectangular_region(OSWindow *os_window, Region region, unsign float src_right_norm = (float)region.right / (float)vw; float src_bottom_norm = (float)(vh - region.bottom) / (float)vh; float src_top_norm = (float)(vh - region.top) / (float)vh; - glUniform4f(program_uniform_location(SCREENSHOT_PROGRAM, "src_rect"), src_left_norm, src_top_norm, src_right_norm, src_bottom_norm); + gpu_uniform4f(program_uniform_location(SCREENSHOT_PROGRAM, "src_rect"), src_left_norm, src_top_norm, src_right_norm, src_bottom_norm); // Set destination rectangle (NDC coordinates: -1 to 1) - glUniform4f(program_uniform_location(SCREENSHOT_PROGRAM, "dest_rect"), -1.0f, -1.0f, 1.0f, 1.0f); + gpu_uniform4f(program_uniform_location(SCREENSHOT_PROGRAM, "dest_rect"), -1.0f, -1.0f, 1.0f, 1.0f); // Set the source texture size for proper downscaling - glUniform2f(program_uniform_location(SCREENSHOT_PROGRAM, "src_size"), (float)vw, (float)vh); + gpu_uniform2f(program_uniform_location(SCREENSHOT_PROGRAM, "src_size"), (float)vw, (float)vh); // Bind the source texture - glActiveTexture(GL_TEXTURE0 + GRAPHICS_UNIT); - glBindTexture(GL_TEXTURE_2D, src_texture); + gpu_bind_texture(GRAPHICS_UNIT, src_texture); // Draw the scaled quad draw_quad(false, 0); // Read the scaled result - glPixelStorei(GL_PACK_ALIGNMENT, 1); - glReadPixels(0, 0, *thumb_w, *thumb_h, GL_RGBA, GL_UNSIGNED_BYTE, dst_buf); - glPixelStorei(GL_PACK_ALIGNMENT, 4); + gpu_read_pixels(0, 0, *thumb_w, *thumb_h, dst_buf); // Restore previous state - bind_framebuffer_for_output(current_framebuffer); + gpu_set_render_target(current_framebuffer); restore_viewport(); // Clean up temporary resources @@ -3580,7 +3436,7 @@ take_screenshot_of_rectangular_region(OSWindow *os_window, Region region, unsign static PyObject * pygpu_driver_version_string(PyObject *self UNUSED, PyObject *args UNUSED) { - return PyUnicode_FromString(global_state.gl_version ? gl_version_string() : ""); + return PyUnicode_FromString(gpu_version_string()); } static void @@ -3731,22 +3587,19 @@ transfer_pipeline_to_struct(PyObject *pg, CustomShaderPipeline *p) { return true; } -static bool -attach_shaders(PyObject *sources, GLuint program_id, GLenum shader_type) { - RAII_ALLOC(const GLchar *, c_sources, calloc(PyTuple_GET_SIZE(sources), sizeof(GLchar *))); +// Concatenate the tuple of source strings into a single string, the returned +// object owns the memory the string points to +static PyObject * +join_shader_sources(PyObject *sources) { for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(sources); i++) { - PyObject *temp = PyTuple_GET_ITEM(sources, i); - if (!PyUnicode_Check(temp)) { + if (!PyUnicode_Check(PyTuple_GET_ITEM(sources, i))) { PyErr_SetString(PyExc_TypeError, "shaders must be strings"); - return false; + return NULL; } - c_sources[i] = PyUnicode_AsUTF8(temp); } - GLuint shader_id = compile_shaders(shader_type, PyTuple_GET_SIZE(sources), c_sources); - if (shader_id == 0) return false; - glAttachShader(program_id, shader_id); - glDeleteShader(shader_id); - return true; + RAII_PyObject(empty, PyUnicode_FromString("")); + if (!empty) return NULL; + return PyUnicode_Join(empty, sources); } static PyObject * @@ -3768,53 +3621,48 @@ compile_program(PyObject UNUSED *self, PyObject *args) { PyErr_Format(PyExc_ValueError, "Unknown program: %d", which); return NULL; } - Program *program = program_ptr(which); if (!PyTuple_GET_SIZE(vertex_shaders)) { if (which == CUSTOM_END_PROGRAM) { free_custom_shader_pipeline(&custom_shaders.end); zero_at_ptr(&custom_shaders.end); custom_shaders.generation++; } - if (program->id != 0) { - glDeleteProgram(program->id); - program->id = 0; - } + set_program_pipeline(which, GPU_NULL_HANDLE); Py_RETURN_NONE; } - if (program->id != 0) { + if (program_pipeline(which)) { if (allow_recompile) { - glDeleteProgram(program->id); - program->id = 0; + set_program_pipeline(which, GPU_NULL_HANDLE); } else { PyErr_SetString(PyExc_ValueError, "program already compiled"); return NULL; } } -#define fail_compile() \ - { \ - glDeleteProgram(program->id); \ - return NULL; \ + RAII_PyObject(vertex_source, join_shader_sources(vertex_shaders)); + if (!vertex_source) return NULL; + RAII_PyObject(fragment_source, join_shader_sources(fragment_shaders)); + if (!fragment_source) return NULL; + Py_ssize_t vsz, fsz; + const char *vcode = PyUnicode_AsUTF8AndSize(vertex_source, &vsz); + if (!vcode) return NULL; + const char *fcode = PyUnicode_AsUTF8AndSize(fragment_source, &fsz); + if (!fcode) return NULL; + const GPUShaderSource sources[2] = { + {.stage = GPU_SHADER_VERTEX, .language = GPU_SHADER_LANGUAGE_GLSL, .code = vcode, .size = (size_t)vsz}, + {.stage = GPU_SHADER_FRAGMENT, .language = GPU_SHADER_LANGUAGE_GLSL, .code = fcode, .size = (size_t)fsz}, + }; + gpu_pipeline_t pipeline = gpu_pipeline_create(sources, arraysz(sources)); + if (!pipeline) { + PyErr_SetString(PyExc_ValueError, gpu_last_error()); + return NULL; } - program->id = glCreateProgram(); - if (!attach_shaders(vertex_shaders, program->id, GL_VERTEX_SHADER)) fail_compile(); - if (!attach_shaders(fragment_shaders, program->id, GL_FRAGMENT_SHADER)) fail_compile(); - glLinkProgram(program->id); - GLint ret = GL_FALSE; - glGetProgramiv(program->id, GL_LINK_STATUS, &ret); - if (ret != GL_TRUE) { - GLsizei len; - static char glbuf[4096]; - glGetProgramInfoLog(program->id, sizeof(glbuf), &len, glbuf); - PyErr_Format(PyExc_ValueError, "Failed to link GLSL shaders:\n%s", glbuf); - fail_compile(); - } -#undef fail_compile + set_program_pipeline(which, pipeline); if (which == CUSTOM_END_PROGRAM) { free_custom_shader_pipeline(&custom_shaders.end); zero_at_ptr(&custom_shaders.end); PyObject *pg = PyDict_GetItemString(metadata, "pipeline"); if (pg && !transfer_pipeline_to_struct(pg, &custom_shaders.end)) { - glDeleteProgram(program->id); + set_program_pipeline(which, GPU_NULL_HANDLE); return NULL; } custom_shaders.end.active = true; @@ -3827,54 +3675,16 @@ compile_program(PyObject UNUSED *self, PyObject *args) { if (g >= 0 && (size_t)g < custom_shaders.end.num_groups) custom_shaders.end.pointer_map_groups |= 1u << g; } if (PyErr_Occurred()) { - glDeleteProgram(program->id); + set_program_pipeline(which, GPU_NULL_HANDLE); return NULL; } } custom_shaders.generation++; } - init_uniforms(which); set_program_layout(which, metadata); - return Py_BuildValue("I", program->id); + Py_RETURN_NONE; } -#define PYWRAP0(name) static PyObject *py##name(PYNOARG) -#define PYWRAP1(name) static PyObject *py##name(PyObject UNUSED *self, PyObject *args) -#define PA(fmt, ...) \ - if (!PyArg_ParseTuple(args, fmt, __VA_ARGS__)) return NULL; -#define ONE_INT(name) \ - PYWRAP1(name) { \ - name(PyLong_AsSsize_t(args)); \ - Py_RETURN_NONE; \ - } -#define TWO_INT(name) \ - PYWRAP1(name) { \ - int a, b; \ - PA("ii", &a, &b); \ - name(a, b); \ - Py_RETURN_NONE; \ - } -#define NO_ARG(name) \ - PYWRAP0(name) { \ - name(); \ - Py_RETURN_NONE; \ - } -#define NO_ARG_INT(name) \ - PYWRAP0(name) { return PyLong_FromSsize_t(name()); } - -ONE_INT(bind_program) -NO_ARG(unbind_program) - -PYWRAP0(create_vao) { - int ans = create_vao(); - if (ans < 0) return NULL; - return Py_BuildValue("i", ans); -} - -ONE_INT(bind_vertex_array) -NO_ARG(unbind_vertex_array) -TWO_INT(unmap_vao_buffer) - static PyObject * sprite_map_set_limits(PyObject UNUSED *self, PyObject *args) { unsigned int w, h; @@ -3890,7 +3700,7 @@ static PyObject * pydecorations_map_new_size(PyObject *self UNUSED, PyObject *args) { unsigned long count, current_capacity, max_size; if (!PyArg_ParseTuple(args, "kkk", &count, ¤t_capacity, &max_size)) return NULL; - GLint w, h; + int32_t w, h; if (!decorations_map_new_size(count, current_capacity, max_size, &w, &h)) Py_RETURN_NONE; return Py_BuildValue("ii", (int)w, (int)h); } @@ -4052,13 +3862,7 @@ pysample_pointer_map(PyObject *self UNUSED, PyObject *args) { static PyMethodDef module_methods[] = { M(compile_program, METH_VARARGS), M(sprite_map_set_limits, METH_VARARGS), - MW(create_vao, METH_NOARGS), MW(gpu_driver_version_string, METH_NOARGS), - MW(bind_vertex_array, METH_O), - MW(unbind_vertex_array, METH_NOARGS), - MW(unmap_vao_buffer, METH_VARARGS), - MW(bind_program, METH_O), - MW(unbind_program, METH_NOARGS), MW(custom_shader_needs_render, METH_VARARGS), MW(decorations_map_new_size, METH_VARARGS), MW(simulate_custom_shader_render_ticks, METH_VARARGS), @@ -4071,7 +3875,10 @@ static PyMethodDef module_methods[] = { void initialize_gpu(void) { - gl_init(); + initialize_gpu_driver(); + GPUCapabilities caps; + gpu_get_capabilities(&caps); + global_state.supports_framebuffer_srgb = caps.supports_srgb_output; query_gpu_texture_limits(); } @@ -4094,6 +3901,7 @@ finalize(void) { default_visual_bell_animation = free_animation(default_visual_bell_animation); free_custom_shader_pipeline(&custom_shaders.end); free_program_layouts(); + unload_gpu_driver(); } bool @@ -4125,55 +3933,6 @@ init_shaders(PyObject *module) { C(MAX_SHADER_ANIM_USER_EVENT_NAME_LEN); C(POINTER_MAP_SIZE); C(GLSL_VERSION); - C(GL_VERSION); - C(GL_VENDOR); - C(GL_SHADING_LANGUAGE_VERSION); - C(GL_RENDERER); - C(GL_TRIANGLE_FAN); - C(GL_TRIANGLE_STRIP); - C(GL_TRIANGLES); - C(GL_LINE_LOOP); - C(GL_COLOR_BUFFER_BIT); - C(GL_VERTEX_SHADER); - C(GL_FRAGMENT_SHADER); - C(GL_TRUE); - C(GL_FALSE); - C(GL_COMPILE_STATUS); - C(GL_LINK_STATUS); - C(GL_MAX_ARRAY_TEXTURE_LAYERS); - C(GL_TEXTURE_BINDING_BUFFER); - C(GL_MAX_TEXTURE_BUFFER_SIZE); - C(GL_MAX_TEXTURE_SIZE); - C(GL_TEXTURE_2D_ARRAY); - C(GL_LINEAR); - C(GL_CLAMP_TO_EDGE); - C(GL_NEAREST); - C(GL_TEXTURE_MIN_FILTER); - C(GL_TEXTURE_MAG_FILTER); - C(GL_TEXTURE_WRAP_S); - C(GL_TEXTURE_WRAP_T); - C(GL_UNPACK_ALIGNMENT); - C(GL_R8); - C(GL_RED); - C(GL_UNSIGNED_BYTE); - C(GL_UNSIGNED_SHORT); - C(GL_R32UI); - C(GL_RGB32UI); - C(GL_RGBA); - C(GL_TEXTURE_BUFFER); - C(GL_STATIC_DRAW); - C(GL_STREAM_DRAW); - C(GL_DYNAMIC_DRAW); - C(GL_SRC_ALPHA); - C(GL_ONE_MINUS_SRC_ALPHA); - C(GL_WRITE_ONLY); - C(GL_READ_ONLY); - C(GL_READ_WRITE); - C(GL_BLEND); - C(GL_FLOAT); - C(GL_UNSIGNED_INT); - C(GL_ARRAY_BUFFER); - C(GL_UNIFORM_BUFFER); C(ANIMATION_SAMPLE_WAIT); #undef C diff --git a/kitty/srgb_gamma.h b/kitty/srgb_gamma.h index 5ac5e172c..3ab7bbf28 100644 --- a/kitty/srgb_gamma.h +++ b/kitty/srgb_gamma.h @@ -1,6 +1,6 @@ // Generated by gen-srgb-lut.py DO NOT edit -static const GLfloat srgb_lut[256] = { +static const float srgb_lut[256] = { 0.00000000f, 0.00030353f, 0.00060705f, 0.00091058f, 0.00121411f, 0.00151763f, 0.00182116f, 0.00212469f, 0.00242822f, 0.00273174f, 0.00303527f, 0.00334654f, 0.00367651f, 0.00402472f, 0.00439144f, 0.00477695f, 0.00518152f, 0.00560539f, 0.00604883f, 0.00651209f, 0.00699541f, 0.00749903f, 0.00802319f, 0.00856813f, 0.00913406f, 0.00972122f, 0.01032982f, 0.01096009f, 0.01161225f, 0.01228649f, 0.01298303f, 0.01370208f, 0.01444384f, 0.01520851f, 0.01599629f, 0.01680738f, 0.01764195f, 0.01850022f, 0.01938236f, 0.02028856f, 0.02121901f, 0.02217388f, 0.02315337f, 0.02415763f, 0.02518686f, 0.02624122f, 0.02732089f, 0.02842604f, diff --git a/kitty/state.c b/kitty/state.c index b7bca2916..c549a3580 100644 --- a/kitty/state.c +++ b/kitty/state.c @@ -6,6 +6,7 @@ */ #include "cleanup.h" +#include "gpu.h" #include "dnd.h" #include "options/to-c-generated.h" #include diff --git a/kitty/state.h b/kitty/state.h index e038bdf59..82a493f22 100644 --- a/kitty/state.h +++ b/kitty/state.h @@ -597,12 +597,18 @@ typedef struct OSWindow { bool has_layout; } background_image; struct { - uint32_t framebuffer_id, attached_texture_generation; - uint32_t extra_fbo_id, extra_fbo_generation; - uint32_t fbo_a_id, fbo_a_generation; - uint32_t fbo_b_id, fbo_b_generation; + gpu_render_target_t framebuffer_id; + uint32_t attached_texture_generation; + gpu_render_target_t extra_fbo_id; + uint32_t extra_fbo_generation; + gpu_render_target_t fbo_a_id; + uint32_t fbo_a_generation; + gpu_render_target_t fbo_b_id; + uint32_t fbo_b_generation; } indirect_output; - uint32_t persist_texture_id, persist_fbo_id, persist_texture_generation; + gpu_texture_t persist_texture_id; + gpu_render_target_t persist_fbo_id; + uint32_t persist_texture_generation; unsigned int active_tab, num_tabs, capacity, last_active_tab, last_num_tabs, last_active_window_id; bool focused_at_last_render, needs_render, needs_layers, input_held; unsigned keep_rendering_till_swap; @@ -714,7 +720,6 @@ typedef struct GlobalState { // Set once an IME composition has been seen, see sync_ime_position_with_cursor() bool ime_used; WindowLogoTable *all_window_logos; - int gl_version; bool supports_framebuffer_srgb; PyObject *options_object; @@ -753,11 +758,16 @@ typedef struct GlobalState { double x, y; } window_being_dragged; struct { - uint32_t texture_id, framebuffer_id, texture_generation; + gpu_texture_t texture_id; + gpu_render_target_t framebuffer_id; + uint32_t texture_generation; int width, height; - uint32_t extra_texture_id, extra_texture_setup_fbo_id; - uint32_t texture_a_id, texture_a_fbo_id; - uint32_t texture_b_id, texture_b_fbo_id; + gpu_texture_t extra_texture_id; + gpu_render_target_t extra_texture_setup_fbo_id; + gpu_texture_t texture_a_id; + gpu_render_target_t texture_a_fbo_id; + gpu_texture_t texture_b_id; + gpu_render_target_t texture_b_fbo_id; } layers_render_texture; } GlobalState; @@ -819,11 +829,8 @@ void upload_gamma_lut(void); bool send_cell_data_to_gpu(ssize_t, Screen *, OSWindow *); void draw_cells(const WindowRenderData *, OSWindow *, bool, bool, bool, Window *, const Window *, monotonic_t); bool update_cursor_trail(CursorTrail *ct, Window *w, monotonic_t now, OSWindow *os_window); -void set_gpu_viewport(unsigned w, unsigned h); -void free_texture(uint32_t *); -void free_framebuffer(uint32_t *); -void send_image_to_gpu(uint32_t *, const void *, int32_t, int32_t, bool, bool, bool, RepeatStrategy); -void send_indexed_image_to_gpu(uint32_t *, const void *, int32_t, int32_t, unsigned, bool); +void send_image_to_gpu(gpu_texture_t *, const void *, int32_t, int32_t, bool, bool, bool, RepeatStrategy); +void send_indexed_image_to_gpu(gpu_texture_t *, const void *, int32_t, int32_t, unsigned, bool); void send_sprite_to_gpu(FONTS_DATA_HANDLE fg, sprite_index, pixel *, sprite_index); void blank_canvas(float, color_type, bool); void blank_os_window(OSWindow *); diff --git a/kitty/window_logo.c b/kitty/window_logo.c index c0899621c..934caf692 100644 --- a/kitty/window_logo.c +++ b/kitty/window_logo.c @@ -7,6 +7,7 @@ #include "state.h" +#include "gpu.h" #include "window_logo.h" #include diff --git a/kitty/window_logo.h b/kitty/window_logo.h index d7a40a252..723ed322f 100644 --- a/kitty/window_logo.h +++ b/kitty/window_logo.h @@ -9,13 +9,14 @@ #include #include #include +#include "../gpu/api.h" typedef unsigned int window_logo_id_t; typedef struct WindowLogo { unsigned int height, width; bool load_from_disk_ok; - uint32_t texture_id; + gpu_texture_t texture_id; uint8_t *bitmap; size_t mmap_size; } WindowLogo; diff --git a/setup.py b/setup.py index bb7ae0448..bfb30285f 100755 --- a/setup.py +++ b/setup.py @@ -809,10 +809,9 @@ def kitty_env(args: Options) -> Env: cflags.extend(pkg_config('harfbuzz', '--cflags-only-I')) platform_libs.extend(pkg_config('harfbuzz', '--libs')) pylib = get_python_flags(args, cflags) - gl_libs = ['-framework', 'OpenGL'] if is_macos else pkg_config('gl', '--libs') libpng = pkg_config('libpng', '--libs') lcms2 = pkg_config('lcms2', '--libs') - ans.ldpaths += pylib + platform_libs + gl_libs + libpng + lcms2 + libcrypto_ldflags + xxhash[1] + ans.ldpaths += pylib + platform_libs + libpng + lcms2 + libcrypto_ldflags + xxhash[1] if is_macos: ans.ldpaths.extend('-framework Cocoa'.split()) elif not is_openbsd: @@ -1189,6 +1188,7 @@ def find_c_files() -> Tuple[List[str], List[str]]: ans.append(os.path.join('kitty', x)) elif ext == '.h': headers.append(os.path.join('kitty', x)) + headers.extend(gpu_api_headers()) ans.append('kitty/vt-parser-dump.c') # ringbuf @@ -1302,6 +1302,33 @@ def build_wayland_protocols( parallel_run(items) +def gpu_api_headers() -> List[str]: + return ['gpu/api.h', 'gpu/opengl/version.h'] + + +def gpu_driver_init_env(env: Env, driver: str = 'opengl') -> Env: + ans = env.copy() + ans.cflags.append('-fPIC') + if driver == 'opengl': + if is_macos: + # 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 + return ans + + +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')) + 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) + + def compile_glfw(compilation_database: CompilationDatabase, build_dsym: bool = False) -> None: modules = 'cocoa' if is_macos else 'x11 wayland' for module in modules.split(): @@ -1478,6 +1505,7 @@ def build(args: Options, native_optimizations: bool = True, call_init: bool = Tr build_dsym=args.build_dsym, ) compile_glfw(args.compilation_database, args.build_dsym) + compile_gpu_drivers(args.compilation_database, args.build_dsym) compile_kittens(args) add_builtin_fonts(args)