Add software rendering as a fallback GPU driver

On Linux and BSD, kitty now falls back to rendering on the CPU with the
Mesa lavapipe (Vulkan) or llvmpipe (OpenGL) software renderers when no
usable GPU is found, such as in virtual machines or with broken GPU
drivers. This is the new software value of the gpu_driver option, last
in the default list.

Drivers are now told which kind of renderer they may use. The software
candidates use only software renderers: Vulkan selects CPU devices and
OpenGL sets LIBGL_ALWAYS_SOFTWARE and __GLX_VENDOR_LIBRARY_NAME while
the renderer is chosen, restoring them afterwards so they are not passed
on to child programs. The other candidates reject software renderers,
unless they are last, so that a working GPU, even one usable only by a
later driver, is always preferred to the CPU. Previously, on systems
with a GPU usable only with OpenGL, kitty would use lavapipe. Drivers
report whether they render in software in their capabilities.

Failing to initialize the GPU driver for the first window is no longer
fatal: the window is recreated with the next driver, as is already done
for failures creating surfaces. OpenGL can only detect that it is using
llvmpipe once a context is current.

When software rendering is used, a message saying so is shown at the
top of every OS window for five seconds after it is first rendered.
This commit is contained in:
Kovid Goyal 2026-11-04 11:29:09 +05:30
parent 70ca44ae1d
commit a8fb53bca4
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C
16 changed files with 363 additions and 44 deletions

View file

@ -53,7 +53,7 @@
#include <stddef.h>
#include <stdint.h>
#define KITTY_GPU_API_VERSION 5u
#define KITTY_GPU_API_VERSION 6u
#define KITTY_GPU_DRIVER_ENTRY_POINT "kitty_gpu_driver_load"
#define GPU_NULL_HANDLE ((uint64_t)0)
@ -68,6 +68,20 @@ typedef uint64_t gpu_surface_t;
typedef void (*gpu_message_func)(const char *message);
// The kinds of renderer a driver may use. Software renderers run on the CPU,
// for example llvmpipe for OpenGL and lavapipe for Vulkan from Mesa. They work
// without a GPU, such as in virtual machines, but are slow.
typedef enum {
GPU_RENDERER_ANY = 1, // use whatever renderer the system provides
// Use only hardware renderers. connect() or initialize() must fail if
// only a software renderer is available, so that kitty can try the next
// driver, see the gpu_driver option.
GPU_RENDERER_HARDWARE,
// Use only software renderers, failing in connect() or initialize() if
// none is available
GPU_RENDERER_SOFTWARE,
} GPURendererKind;
typedef struct GPUDriverInitParams {
// Enable extra error checking and debug output
bool debug_rendering;
@ -77,6 +91,8 @@ typedef struct GPUDriverInitParams {
gpu_message_func debug_print;
// Report an unrecoverable error, must not return
gpu_message_func fatal;
// The kind of renderer to use
GPURendererKind renderer;
// X11: The windowing system installs a process wide X error handler, so
// drivers must not install their own. Instead, to detect errors caused by
// their requests, they call x11_push_error_trap() before making the
@ -101,6 +117,8 @@ typedef struct GPUCapabilities {
// this, such as the one byte selection state of cells, must be stored
// with each element padded to this size.
uint32_t vertex_input_alignment;
// Whether rendering is done on the CPU by a software renderer
bool is_software;
} GPUCapabilities;
// }}}
@ -346,7 +364,9 @@ typedef struct GPUDriverAPI {
bool (*connect)(void *driver, const GPUNativeWindow *display);
// Called once, when the first surface has been created and made current.
// Must be called before any other function except connect(), destroy(),
// last_error() and the surface functions.
// last_error() and the surface functions. If it returns false,
// last_error() describes the problem and kitty destroys the surface,
// unloads the driver and tries the next one.
bool (*initialize)(void *driver);
void (*destroy)(void *driver);
// A description of the last error, never NULL

View file

@ -114,6 +114,10 @@ connect_to_display(void *driver, const GPUNativeWindow *display) {
set_error(d, "The Metal driver supports only Cocoa");
return false;
}
if (d->params.renderer == GPU_RENDERER_SOFTWARE) {
set_error(d, "Metal has no software renderer");
return false;
}
@autoreleasepool {
d->device = choose_device(d);
if (d->device == nil) {
@ -199,6 +203,7 @@ get_capabilities(void *driver, GPUCapabilities *ans) {
// Any texture can be viewed with the sRGB variant of its pixel format, including drawables
ans->supports_srgb_output = d->device != nil;
ans->vertex_input_alignment = VERTEX_INPUT_ALIGNMENT;
ans->is_software = false; // Metal always renders on a GPU
}
// }}}

View file

@ -7,10 +7,12 @@
// The OpenGL implementation of the kitty GPU driver API, see ../api.h
#define _GNU_SOURCE // for setenv(), unsetenv() and strdup() with glibc, has no effect on Darwin
#include "../api.h"
#include "platform.h"
#include "version.h"
#include "gl-wrapper.h"
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
@ -90,7 +92,7 @@ typedef struct Driver {
const GLPlatform *platform;
Surface *current_surface;
Pipeline *current_pipeline;
bool initialized, supports_srgb_output;
bool initialized, supports_srgb_output, is_software;
int gl_version;
GLint max_texture_size, max_array_texture_layers;
char last_error[8192];
@ -199,9 +201,112 @@ shader_target(void *driver UNUSED) {
return "glsl-" STRINGIFY(GLSL_VERSION);
}
// Software renderers {{{
// Mesa chooses its software renderer, llvmpipe, when LIBGL_ALWAYS_SOFTWARE is
// set. With libglvnd, other vendors, such as NVIDIA, can claim the X11 screen
// first unless the vendor is forced to be Mesa. These variables are read when
// EGL or GLX is initialized for the display and when contexts are created, so
// they are set in connect() and restored once the driver is initialized, to
// avoid passing them on to programs run by kitty. Both libglvnd and Mesa cache
// GLX state per X11 display connection, so they have no effect if GLX was
// already used on the display, for example by a previous OpenGL driver that
// was rejected.
typedef struct EnvOverride {
const char *name, *value;
char *saved;
bool was_set;
} EnvOverride;
static EnvOverride software_env[] = {
{.name = "LIBGL_ALWAYS_SOFTWARE", .value = "1"},
{.name = "__GLX_VENDOR_LIBRARY_NAME", .value = "mesa"},
};
static bool software_env_applied = false;
static void
restore_software_env(Driver *d) {
if (!software_env_applied) return;
for (size_t i = 0; i < arraysz(software_env); i++) {
EnvOverride *e = software_env + i;
const int ret = e->was_set ? setenv(e->name, e->saved, 1) : unsetenv(e->name);
if (ret != 0) log_error(d, "Failed to restore the environment variable %s with error: %s", e->name, strerror(errno));
free(e->saved);
e->saved = NULL;
e->was_set = false;
}
software_env_applied = false;
}
#ifndef __APPLE__
static bool
initialize(void *driver) {
Driver *d = driver;
apply_software_env(Driver *d) {
if (software_env_applied) return true;
for (size_t i = 0; i < arraysz(software_env); i++) {
EnvOverride *e = software_env + i;
const char *current = getenv(e->name);
e->was_set = current != NULL;
e->saved = NULL;
if (current && !(e->saved = strdup(current))) {
set_error(d, "Out of memory saving the environment variable %s", e->name);
software_env_applied = true; // restore the variables already set
restore_software_env(d);
return false;
}
software_env_applied = true;
if (setenv(e->name, e->value, 1) != 0) {
set_error(d, "Failed to set the environment variable %s with error: %s", e->name, strerror(errno));
restore_software_env(d);
return false;
}
}
return true;
}
#endif
static bool
is_software_renderer(const char *renderer) {
// The GL_RENDERER strings of the software renderers from Mesa and Apple
static const char *const names[] = {"llvmpipe", "softpipe", "swrast", "Software Rasterizer", "Apple Software Renderer"};
for (size_t i = 0; i < arraysz(names); i++) {
if (strstr(renderer, names[i])) return true;
}
return false;
}
// }}}
static bool
check_renderer_kind(Driver *d) {
const char *renderer = (const char *)glGetString(GL_RENDERER);
if (!renderer) {
set_error(d, "Failed to query the OpenGL renderer");
return false;
}
d->is_software = is_software_renderer(renderer);
if (d->params.debug_rendering) {
char buf[1024];
snprintf(buf, sizeof(buf), "GL renderer: %s%s", renderer, d->is_software ? " (software)" : "");
d->params.debug_print(buf);
}
switch (d->params.renderer) {
case GPU_RENDERER_ANY: break;
case GPU_RENDERER_HARDWARE:
if (d->is_software) {
set_error(d, "The OpenGL renderer: %s is a software renderer", renderer);
return false;
}
break;
case GPU_RENDERER_SOFTWARE:
if (!d->is_software) {
set_error(d, "The OpenGL renderer: %s is not a software renderer, the Mesa llvmpipe driver may not be installed", renderer);
return false;
}
break;
}
return true;
}
static bool
initialize_impl(Driver *d) {
if (d->initialized) return true;
if (!d->platform || !d->current_surface) {
set_error(d, "The OpenGL driver must have a current surface before it can be initialized");
@ -244,6 +349,10 @@ initialize(void *driver) {
d->initialized = false;
return false;
}
if (!check_renderer_kind(d)) {
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__
@ -255,10 +364,20 @@ initialize(void *driver) {
return true;
}
static bool
initialize(void *driver) {
Driver *d = driver;
const bool ok = initialize_impl(d);
// The renderer has been chosen, see apply_software_env()
restore_software_env(d);
return ok;
}
static void release_native_resources(void *driver);
static void
destroy(void *driver) {
restore_software_env(driver);
release_native_resources(driver);
if (the_driver == driver) the_driver = NULL;
free(driver);
@ -271,6 +390,7 @@ get_capabilities(void *driver, GPUCapabilities *ans) {
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;
ans->vertex_input_alignment = 1;
ans->is_software = d->is_software;
}
// }}}
@ -1082,7 +1202,17 @@ ensure_platform(Driver *d, GPUPlatform type) {
static bool
connect_to_display(void *driver, const GPUNativeWindow *display) {
return ensure_platform(driver, display->platform);
Driver *d = driver;
if (!ensure_platform(d, display->platform)) return false;
if (d->params.renderer == GPU_RENDERER_SOFTWARE) {
#ifdef __APPLE__
set_error(d, "Software rendering with OpenGL is not supported on macOS");
return false;
#else
return apply_software_env(d);
#endif
}
return true;
}
static bool

View file

@ -288,6 +288,10 @@ unsuitable_device(Driver *d, VkPhysicalDevice dev, uint32_t *queue_family, bool
static char reason[512];
VkPhysicalDeviceProperties props;
vkGetPhysicalDeviceProperties(dev, &props);
// Software renderers, such as lavapipe, report themselves as CPU devices
const bool is_software = props.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU;
if (d->params.renderer == GPU_RENDERER_HARDWARE && is_software) return "it is a software renderer";
if (d->params.renderer == GPU_RENDERER_SOFTWARE && !is_software) return "it is not a software renderer";
if (props.apiVersion < VK_MAKE_API_VERSION(0, VULKAN_REQUIRED_VERSION_MAJOR, VULKAN_REQUIRED_VERSION_MINOR, 0)) {
snprintf(reason, sizeof(reason), "it supports only Vulkan %u.%u", VK_API_VERSION_MAJOR(props.apiVersion), VK_API_VERSION_MINOR(props.apiVersion));
return reason;
@ -540,6 +544,7 @@ get_capabilities(void *driver, GPUCapabilities *ans) {
ans->supports_srgb_output = d->has_swapchain_mutable_format;
// Vulkan places no alignment requirements on vertex input offsets and strides
ans->vertex_input_alignment = 1;
ans->is_software = d->properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU;
}
// }}}

View file

@ -1223,6 +1223,14 @@ render_os_window(OSWindow *w, monotonic_t now, bool scan_for_animated_images) {
needs_render = true;
if (w->last_active_window_id != active_window_id || w->last_active_tab != w->active_tab || w->focused_at_last_render != w->is_focused) needs_render = true;
if (w->render_calls < 3 && background_image_for_os_window(w) != NULL) needs_render = true;
if (w->software_rendering_banner.shown && !w->software_rendering_banner.done) {
// Redraw the window without the banner once it expires
const monotonic_t expires_at = w->software_rendering_banner.shown_at + SOFTWARE_RENDERING_BANNER_DURATION;
if (now >= expires_at) {
w->software_rendering_banner.done = true;
needs_render = true;
} else set_maximum_wait(expires_at - now);
}
if (needs_render) render_prepared_os_window(w, active_window_id, active_window_bg, num_visible_windows, all_windows_have_same_bg, now);
if (w->is_focused) change_menubar_title(w->window_title);
return needs_render;

View file

@ -237,14 +237,23 @@ def gpu_driver_path(driver: str = 'opengl') -> str:
return os.path.join(extensions_dir, f'{prefix}{driver}.so')
def available_gpu_drivers(names: Iterable[str]) -> list[tuple[str, str]]:
# The (name, path) of the specified GPU drivers that are present in this
# build of kitty, in the specified order
# The drivers that can render using a software renderer, used for the software
# value of the gpu_driver option, in order of preference. macOS has no
# software renderers for Metal and modern OpenGL.
SOFTWARE_GPU_DRIVERS = () if is_macos else ('vulkan', 'opengl')
def available_gpu_drivers(names: Iterable[str]) -> list[tuple[str, str, bool]]:
# The (name, path, software) of the specified GPU drivers that are present
# in this build of kitty, in the specified order. software is True for the
# drivers that must use a software renderer, from the software value.
ans = []
for name in names:
path = gpu_driver_path(name)
if os.path.exists(path):
ans.append((name, path))
software = name == 'software'
for driver in SOFTWARE_GPU_DRIVERS if software else (name,):
path = gpu_driver_path(driver)
if os.path.exists(path):
ans.append((driver, path, software))
return ans

View file

@ -641,7 +641,7 @@ def glfw_terminate() -> None:
def glfw_init(
path: str,
gpu_drivers: Sequence[tuple[str, str]], # (name, path) of the GPU drivers to try in order
gpu_drivers: Sequence[tuple[str, str, bool]], # (name, path, software) of the GPU drivers to try in order
edge_spacing_func: Callable[[EdgeLiteral], float],
debug_keyboard: bool = False,
debug_rendering: bool = False,

View file

@ -2589,8 +2589,15 @@ create_os_window(PyObject UNUSED *self, PyObject *args, PyObject *kw) {
return NULL;
}
}
if (is_first_window && !initialize_gpu()) {
GPUFailure failure;
describe_gpu_failure(failure, "initialize the GPU");
gpu_surface_destroy(gpu_surface);
glfwDestroyWindow(glfw_window);
if (switch_gpu_driver_after_failure(is_first_window, failure)) return create_os_window(self, args, kw);
return NULL;
}
glfwSetNativeSurfaceChangedCallback(glfw_window, native_surface_changed_callback);
if (is_first_window) initialize_gpu();
bool is_semi_transparent = glfwGetWindowAttrib(glfw_window, GLFW_TRANSPARENT_FRAMEBUFFER);
// blank the window once so that there is no initial flash of color
// changing, in case the background color is not black
@ -2877,10 +2884,10 @@ dbus_monitor_session_state(PyObject *self UNUSED, PyObject *callback) {
}
#endif
// Parse a sequence of (name, path) pairs of GPU drivers into candidates
// Parse a sequence of (name, path, software) tuples of GPU drivers into candidates
static bool
set_gpu_drivers(PyObject *gpu_drivers, bool debug_rendering) {
RAII_PyObject(seq, PySequence_Fast(gpu_drivers, "gpu_drivers must be a sequence of (name, path) pairs"));
RAII_PyObject(seq, PySequence_Fast(gpu_drivers, "gpu_drivers must be a sequence of (name, path, software) tuples"));
if (!seq) return false;
const Py_ssize_t n = PySequence_Fast_GET_SIZE(seq);
RAII_ALLOC(GPUDriverCandidate, items, calloc(MAX(1, n), sizeof(GPUDriverCandidate)));
@ -2889,7 +2896,9 @@ set_gpu_drivers(PyObject *gpu_drivers, bool debug_rendering) {
return false;
}
for (Py_ssize_t i = 0; i < n; i++) {
if (!PyArg_ParseTuple(PySequence_Fast_GET_ITEM(seq, i), "ss", &items[i].name, &items[i].path)) return false;
int software = 0;
if (!PyArg_ParseTuple(PySequence_Fast_GET_ITEM(seq, i), "ssp", &items[i].name, &items[i].path, &software)) return false;
items[i].software = software != 0;
}
if (!set_gpu_driver_candidates(items, (size_t)n, debug_rendering)) {
PyErr_NoMemory();

View file

@ -41,7 +41,7 @@ driver_x11_pop_error_trap(void) {
}
const char *
load_gpu_driver(const char *path, bool debug_rendering) {
load_gpu_driver(const char *path, bool debug_rendering, GPURendererKind renderer) {
static char errbuf[2048];
if (gpu_driver.driver) return NULL;
void *handle = dlopen(path, RTLD_LAZY | RTLD_LOCAL);
@ -62,6 +62,7 @@ load_gpu_driver(const char *path, bool debug_rendering) {
.log_error = driver_log_error,
.debug_print = driver_debug_print,
.fatal = driver_fatal,
.renderer = renderer,
.x11_push_error_trap = driver_x11_push_error_trap,
.x11_pop_error_trap = driver_x11_pop_error_trap,
};
@ -104,6 +105,7 @@ set_gpu_driver_candidates(const GPUDriverCandidate *items, size_t count, bool de
GPUDriverCandidate *c = candidates.items + candidates.count++;
c->name = strdup(items[i].name);
c->path = strdup(items[i].path);
c->software = items[i].software;
if (!c->name || !c->path) return false;
}
return true;
@ -132,29 +134,35 @@ load_next_gpu_driver(const GPUNativeWindow *display) {
}
while (candidates.next < candidates.count) {
const GPUDriverCandidate *c = candidates.items + candidates.next++;
const char *err = load_gpu_driver(c->path, candidates.debug_rendering);
const bool is_last = candidates.next >= candidates.count;
// Hardware candidates skip software renderers, so that a GPU usable
// by a later candidate is preferred to rendering on the CPU. The last
// candidate takes whatever is available rather than failing.
const GPURendererKind renderer = c->software ? GPU_RENDERER_SOFTWARE : (is_last ? GPU_RENDERER_ANY : GPU_RENDERER_HARDWARE);
const char *kind = c->software ? " (software)" : "";
const char *err = load_gpu_driver(c->path, candidates.debug_rendering, renderer);
if (!err) {
if (gpu_driver.api.connect(gpu_driver.driver, display)) {
if (candidates.debug_rendering) timed_debug_print("Using the %s GPU driver\n", c->name);
if (candidates.debug_rendering) timed_debug_print("Using the %s%s GPU driver\n", c->name, kind);
return NULL;
}
err = gpu_last_error();
}
if (candidates.debug_rendering) timed_debug_print("The %s GPU driver is not usable: %s\n", c->name, err);
add_error("%sThe %s GPU driver is not usable: %s", pos ? "\n" : "", c->name, err);
if (candidates.debug_rendering) timed_debug_print("The %s%s GPU driver is not usable: %s\n", c->name, kind, err);
add_error("%sThe %s%s GPU driver is not usable: %s", pos ? "\n" : "", c->name, kind, err);
if (gpu_driver.driver) unload_gpu_driver();
}
#undef add_error
return errbuf;
}
void
const char *
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));
if (gpu_driver.initialized) return NULL;
if (!gpu_driver.driver) return "Cannot initialize the GPU as no GPU driver has been loaded";
if (!gpu_driver.api.initialize(gpu_driver.driver)) return gpu_driver.api.last_error(gpu_driver.driver);
gpu_driver.initialized = true;
return NULL;
}
void

View file

@ -24,12 +24,16 @@ typedef struct GPUDriver {
extern GPUDriver gpu_driver;
// Load the GPU driver shared library at path. Returns NULL on success or an error message.
const char *load_gpu_driver(const char *path, bool debug_rendering);
const char *load_gpu_driver(const char *path, bool debug_rendering, GPURendererKind renderer);
// Choosing between GPU drivers {{{
// The drivers to try, in order of preference, see the gpu_driver option
typedef struct GPUDriverCandidate {
const char *name, *path;
// Use only a software renderer with this driver. Candidates that are not
// software are restricted to hardware renderers, unless they are the
// last candidate.
bool software;
} GPUDriverCandidate;
// Remember the drivers to try. Copies the strings.
@ -43,8 +47,9 @@ const char *load_next_gpu_driver(const GPUNativeWindow *display);
bool has_untried_gpu_drivers(void);
// }}}
// Must be called once a surface has been created and made current, before any
// other GPU functions, except the surface functions, are used
void initialize_gpu_driver(void);
// other GPU functions, except the surface functions, are used. Returns NULL on
// success or an error message.
const char *initialize_gpu_driver(void);
void unload_gpu_driver(void);
// Driver API wrappers {{{

View file

@ -1572,7 +1572,7 @@ some slight input latency. If so, set this to :code:`no`.
opt(
'gpu_driver',
'metal vulkan opengl',
'metal vulkan opengl software',
option_type='gpu_driver',
long_text="""
The GPU drivers kitty uses to render, as a space or comma separated list, in
@ -1580,6 +1580,18 @@ order of preference. kitty uses the first driver in the list that works on your
system, skipping drivers that are not available on your platform or were not
included in the build of kitty. The available drivers are: :code:`metal`
(macOS), :code:`vulkan` (Linux and BSD) and :code:`opengl` (all platforms).
The special value :code:`software` renders on the CPU, without a GPU, using
the software renderers of the Mesa graphics library, lavapipe for Vulkan and
llvmpipe for OpenGL, which must be installed. This is useful in virtual
machines and on systems without a GPU or with broken GPU drivers, but is
slow. It is available only on Linux and BSD. The other drivers skip
software renderers, so that a working GPU is always preferred, unless they
are last in the list. Remove :code:`software` from the list to never use
software rendering, or put it first to always use it. When software rendering
is used, kitty shows a message saying so for a few seconds in every new OS
window.
Use :option:`kitty --debug-rendering` to see which driver is used and why
others were rejected. Changing this option by reloading the config is not
supported.

View file

@ -602,7 +602,7 @@ class Options:
force_ltr: bool = False
foreground: Color = Color(221, 221, 221)
forward_stdio: bool = False
gpu_driver: tuple[str, ...] = ('metal', 'vulkan', 'opengl')
gpu_driver: tuple[str, ...] = ('metal', 'vulkan', 'opengl', 'software')
hide_window_decorations: int = 0
hyperlink_target_position: choices_for_hyperlink_target_position = 'top'
inactive_border_color: Color = Color(204, 204, 204)

View file

@ -1034,7 +1034,7 @@ def clipboard_control(x: str) -> tuple[str, ...]:
return tuple(x.lower().split())
GPU_DRIVERS = ('metal', 'vulkan', 'opengl')
GPU_DRIVERS = ('metal', 'vulkan', 'opengl', 'software')
def gpu_driver(x: str) -> tuple[str, ...]:

View file

@ -2647,14 +2647,101 @@ gpu_data_for_centered_image(ImageRenderData *ans, unsigned int screen_width_px,
gpu_data_for_image(ans, -1 + hmargin, -1 + vmargin, -1 + hmargin + width_frac, -1 + vmargin + height_frac);
}
// Colors are passed to the shader as linear values, unless linear is false,
// for render targets that do not encode the output to sRGB.
static void
draw_alpha_mask(ImageRenderData *data, color_type fg, color_type bg, float background_opacity, bool linear) {
bind_program(GRAPHICS_ALPHA_MASK_PROGRAM);
const int32_t fg_loc = program_param(GRAPHICS_ALPHA_MASK_PROGRAM, "amask_fg"), bg_loc = program_param(GRAPHICS_ALPHA_MASK_PROGRAM, "amask_bg_premult");
if (linear) {
color_vec3(fg_loc, fg);
color_vec4_premult(bg_loc, bg, background_opacity);
} else {
#define C(color, shift) (((color >> shift) & 0xff) / 255.f)
param_3f(fg_loc, C(fg, 16), C(fg, 8), C(fg, 0));
param_4f(bg_loc, C(bg, 16) * background_opacity, C(bg, 8) * background_opacity, C(bg, 0) * background_opacity, background_opacity);
#undef C
}
draw_graphics(GRAPHICS_ALPHA_MASK_PROGRAM, data, 0, 1, 1.0);
}
static void
draw_centered_alpha_mask(size_t screen_width, size_t screen_height, size_t width, size_t height, uint8_t *canvas, float background_opacity) {
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);
color_vec3(program_param(GRAPHICS_ALPHA_MASK_PROGRAM, "amask_fg"), OPT(foreground));
color_vec4_premult(program_param(GRAPHICS_ALPHA_MASK_PROGRAM, "amask_bg_premult"), OPT(background), background_opacity);
draw_graphics(GRAPHICS_ALPHA_MASK_PROGRAM, data, 0, 1, 1.0);
draw_alpha_mask(data, OPT(foreground), OPT(background), background_opacity, true);
}
// Render lines of text, each centered horizontally, into a single alpha mask
// surrounded by padding pixels on every side. Returns a canvas with a NULL
// pointer on failure.
static StringCanvas
render_centered_lines(FONTS_DATA_HANDLE fonts_data, const char *const *lines, size_t num_lines, size_t padding) {
StringCanvas ans = {0}, rendered[4] = {0};
if (num_lines > arraysz(rendered)) return ans;
size_t width = 0, height = 0;
bool ok = true;
for (size_t i = 0; i < num_lines && ok; i++) {
rendered[i] = render_simple_text(fonts_data, lines[i]);
if (!rendered[i].canvas) ok = false;
else {
width = MAX(width, rendered[i].width);
height += rendered[i].height;
}
}
if (ok) {
ans.width = width + 2 * padding;
ans.height = height + 2 * padding;
ans.canvas = calloc(ans.width * ans.height, 1);
if (ans.canvas) {
size_t y = padding;
for (size_t i = 0; i < num_lines; i++) {
const size_t x = padding + (width - rendered[i].width) / 2;
for (size_t r = 0; r < rendered[i].height; r++, y++)
memcpy(ans.canvas + y * ans.width + x, rendered[i].canvas + r * rendered[i].width, rendered[i].width);
}
}
}
for (size_t i = 0; i < num_lines; i++) free(rendered[i].canvas);
if (!ans.canvas) ans = (StringCanvas){0};
return ans;
}
// Tell the user that software rendering is in use, see the gpu_driver option.
// Shown at the top of every OS window for SOFTWARE_RENDERING_BANNER_DURATION
// after it is first rendered, render_os_window() redraws the window to remove it.
static void
draw_software_rendering_banner(OSWindow *w, monotonic_t now) {
if (!global_state.software_rendering || w->software_rendering_banner.done || w->live_resize.in_progress || !w->fonts_data) return;
if (!w->software_rendering_banner.shown) {
w->software_rendering_banner.shown = true;
w->software_rendering_banner.shown_at = now;
}
static const char *const lines[] = {"Software rendering is in use,", "so kitty will be slow"};
const size_t padding = MAX(4u, w->fonts_data->fcm.cell_height / 2);
StringCanvas banner = render_centered_lines(w->fonts_data, lines, arraysz(lines), padding);
if (!banner.canvas) {
log_error("Failed to render the software rendering banner");
w->software_rendering_banner.done = true;
return;
}
const float vw = (float)w->viewport_width, vh = (float)w->viewport_height;
if (vw > 0 && vh > 0) {
ImageRenderData *data = load_alpha_mask_texture(banner.width, banner.height, banner.canvas);
// In normalized device coordinates, horizontally centered, a little below the top edge
const float half_width = MIN(1.f, banner.width / vw);
const float top = MIN(1.f, -1.f + 2.f * padding / vh), bottom = MIN(1.f, top + 2.f * banner.height / vh);
gpu_data_for_image(data, -half_width, top, half_width, bottom);
save_viewport(0, 0, w->viewport_width, w->viewport_height);
// Drawn directly into the window, after any layers have been composited
const bool srgb = global_state.supports_framebuffer_srgb;
if (srgb) gpu_set_srgb_output(true);
// Inverted colors, so that it stands out from the terminal contents
draw_alpha_mask(data, OPT(background), OPT(foreground), 1.f, srgb);
if (srgb) gpu_set_srgb_output(false);
restore_viewport();
}
free(banner.canvas);
}
static void
@ -3308,6 +3395,7 @@ stop_os_window_rendering(OSWindow *os_window, Tab *tab, Window *active_window, m
draw_resizing_text(os_window);
}
}
draw_software_rendering_banner(os_window, now);
os_window->last_rendered_at = now;
os_window->frame_counter++;
}
@ -3429,7 +3517,7 @@ pyload_gpu_driver(PyObject *self UNUSED, PyObject *args) {
const char *path;
int debug_rendering = 0;
if (!PyArg_ParseTuple(args, "s|p", &path, &debug_rendering)) return NULL;
const char *err = load_gpu_driver(path, debug_rendering != 0);
const char *err = load_gpu_driver(path, debug_rendering != 0, GPU_RENDERER_ANY);
if (err) {
PyErr_SetString(PyExc_OSError, err);
return NULL;
@ -3878,14 +3966,17 @@ static PyMethodDef module_methods[] = {
{NULL, NULL, 0, NULL} /* Sentinel */
};
void
bool
initialize_gpu(void) {
initialize_gpu_driver();
GPUCapabilities caps;
if (initialize_gpu_driver()) return false;
GPUCapabilities caps = {0};
gpu_get_capabilities(&caps);
global_state.supports_framebuffer_srgb = caps.supports_srgb_output;
global_state.software_rendering = caps.is_software;
if (caps.is_software) log_error("Using software rendering with the %s GPU driver, kitty will be slow", gpu_driver_name());
selection_stride = MAX((size_t)1u, (size_t)caps.vertex_input_alignment);
query_gpu_texture_limits();
return true;
}
void

View file

@ -587,6 +587,11 @@ typedef struct OSWindow {
int x, y, w, h;
bool is_set, was_maximized;
} before_fullscreen;
// The message shown when software rendering is used, see draw_software_rendering_banner()
struct {
monotonic_t shown_at;
bool shown, done;
} software_rendering_banner;
int viewport_width, viewport_height, window_width, window_height;
double viewport_x_ratio, viewport_y_ratio;
Tab *tabs;
@ -722,6 +727,8 @@ typedef struct GlobalState {
bool ime_used;
WindowLogoTable *all_window_logos;
bool supports_framebuffer_srgb;
// Rendering is done on the CPU, see the software value of the gpu_driver option
bool software_rendering;
PyObject *options_object;
struct {
@ -791,7 +798,10 @@ sprite_index_to_pos(unsigned idx, unsigned xnum, unsigned ynum, unsigned *x, uns
}
void initialize_gpu(void);
// How long the message shown when software rendering is used stays up
#define SOFTWARE_RENDERING_BANNER_DURATION s_double_to_monotonic_t(5.0)
// Initialize the GPU driver, returns false on failure, with the error available from gpu_last_error()
bool initialize_gpu(void);
void free_vao(ssize_t vao_idx);
void cleanup_shader_resources_on_terminate(void);
bool remove_os_window(id_type os_window_id);

View file

@ -6,7 +6,7 @@ import shutil
import subprocess
import tempfile
from kitty.constants import kitty_exe
from kitty.constants import SOFTWARE_GPU_DRIVERS, available_gpu_drivers, gpu_driver_path, kitty_exe
from kitty.fast_data_types import Color, test_cursor_blink_easing_function
from kitty.options.utils import DELETE_ENV_VAR, EasingFunction, build_action_aliases, to_color
from kitty.utils import log_error, shlex_split
@ -404,8 +404,15 @@ def conf_parsing(self):
opts = p('font_size 11.37', 'clear_all_shortcuts y', 'color23 red')
self.ae(opts.font_size, 11.37)
self.ae(defaults.gpu_driver, ('metal', 'vulkan', 'opengl'))
self.ae(defaults.gpu_driver, ('metal', 'vulkan', 'opengl', 'software'))
self.ae(p('gpu_driver vulkan, opengl opengl').gpu_driver, ('vulkan', 'opengl'))
self.ae(p('gpu_driver software opengl').gpu_driver, ('software', 'opengl'))
present = {name for name in ('metal', 'vulkan', 'opengl') if os.path.exists(gpu_driver_path(name))}
self.ae(
available_gpu_drivers(defaults.gpu_driver),
[(name, gpu_driver_path(name), False) for name in ('metal', 'vulkan', 'opengl') if name in present]
+ [(name, gpu_driver_path(name), True) for name in SOFTWARE_GPU_DRIVERS if name in present],
)
self.ae(p('gpu_driver opengl,vulkan').gpu_driver, ('opengl', 'vulkan'))
self.ae(p('gpu_driver directx opengl', bad_line_num=1).gpu_driver, defaults.gpu_driver)
radius_opts = p('window_border_radius 7px')