From 21e84451d0b8a4b67e1494c22173296eb2e8e010 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Tue, 3 Nov 2026 21:53:01 +0530 Subject: [PATCH] Use the coordinate conventions of Vulkan and Metal for the GPU API Pixel coordinates of viewports, scissor rectangles and read back pixels now have their origin at the top left of the render target, rows are read back top to bottom, NDC y=-1 is the top of the viewport and render targets have their top row at texture coordinate t=0, the same as uploaded images. Vulkan and Metal drivers can then render with no flips at all. The OpenGL driver is now the special case. Framebuffer objects already behave this way, so it converts only when rendering to a window: vertex shaders negate gl_Position.y via a kitty_flip_y uniform that the GLSL fixup adds, viewport and scissor y coordinates are converted, rows of read back pixels are reversed and copying to a texture uses a flipping blit. kitty's code gets simpler: viewports and scissor rectangles no longer need the framebuffer height, screenshots no longer need their rows flipped and textures produced by rendering are sampled the same way as uploaded ones. The rounded rect shader no longer uses SV_Position, whose origin differs between backends. User facing custom shader UV coordinates are unchanged, still with their origin at the bottom left. Rendering is pixel identical to before. --- gpu/api.h | 14 ++- gpu/opengl/driver.c | 183 +++++++++++++++++++++++----- kitty/cursor_trail.c | 8 +- kitty/gpu.c | 19 +-- kitty/gpu.h | 7 +- kitty/graphics.c | 21 ++-- kitty/graphics.h | 9 +- kitty/rc/screenshot.py | 2 +- kitty/screen.c | 2 +- kitty/shaders.c | 175 +++++++++++++------------- kitty/shaders/background.slang | 7 +- kitty/shaders/custom/pipeline.slang | 22 ++-- kitty/shaders/custom/types.slang | 20 +-- kitty/shaders/padding.slang | 3 +- kitty/shaders/rounded_rect.slang | 30 +++-- kitty/shaders/slang.py | 11 ++ kitty/shaders/trail.slang | 3 +- kitty/state.c | 2 +- kitty_tests/graphics.py | 54 ++++---- kitty_tests/slang.py | 9 ++ 20 files changed, 372 insertions(+), 229 deletions(-) diff --git a/gpu/api.h b/gpu/api.h index 510e24866..f2d321be2 100644 --- a/gpu/api.h +++ b/gpu/api.h @@ -23,11 +23,15 @@ // functions that can fail return false. In both cases a description of the // failure is available from last_error(). Errors from which the driver // cannot recover are reported via the fatal() callback in GPUDriverInitParams. -// * Pixel coordinates for viewports, scissor rectangles and reading back pixels -// have their origin at the bottom left corner of the current render target, -// with y increasing upwards. Rows of pixel data read back from the GPU are -// ordered bottom to top. Pixel data uploaded to textures is ordered with the -// first row at texture coordinate t=0. +// * Coordinates follow the conventions of Vulkan and Metal. Pixel coordinates +// for viewports, scissor rectangles and reading back pixels have their +// origin at the top left corner of the current render target, with y +// increasing downwards. Rows of pixel data read back from the GPU are +// ordered top to bottom. In normalized device coordinates, y=-1 is the top +// of the viewport and y=1 the bottom. The first row of a texture, at +// texture coordinate t=0, is the first row of uploaded pixel data and the +// top row of a render target drawing into the texture. Drivers for APIs with +// other conventions, such as OpenGL, must convert. // * The driver tracks a small amount of "current" state: the pipeline, // vertex layout, render target, viewport, scissor rectangle, sRGB output // mode and textures bound to texture units. Draw calls use this state. This diff --git a/gpu/opengl/driver.c b/gpu/opengl/driver.c index 59b61b145..5be154787 100644 --- a/gpu/opengl/driver.c +++ b/gpu/opengl/driver.c @@ -59,6 +59,9 @@ typedef struct NativeName { typedef struct Pipeline { GLuint id; + // The location of the kitty_flip_y uniform, see flip_y_for_window(), and its current value, zero if unset + GLint flip_y_location; + GLfloat flip_y; ParamBlock *param_blocks; size_t num_param_blocks; // Maps Slang names to GLSL identifiers @@ -66,10 +69,27 @@ typedef struct Pipeline { size_t num_native_names; } Pipeline; +// OpenGL puts the origin of window framebuffers at the bottom left, unlike +// the GPU API, see gpu/api.h, while framebuffer objects have the first row of +// their texture at the origin, which matches the API. So when rendering to a +// window the driver flips: shaders negate gl_Position.y (see +// fixup_opengl_code() in kitty/shaders/slang.py), y co-ordinates of +// viewports, scissor rectangles and read back pixels are converted and rows +// of read back pixels are reversed. This needs the height of the window +// framebuffer, which is tracked here. +typedef struct Surface { + GLSurface *gl; + uint32_t width, height; + // The framebuffer object bound in the context of this surface by + // set_render_target(), zero for the window + GLuint render_target; +} Surface; + typedef struct Driver { GPUDriverInitParams params; const GLPlatform *platform; - GLSurface *current_surface; + Surface *current_surface; + Pipeline *current_pipeline; bool initialized, supports_srgb_output; int gl_version; GLint max_texture_size, max_array_texture_layers; @@ -85,7 +105,7 @@ static Driver *the_driver = NULL; #define AS_TEXTURE(handle) ((Texture *)(uintptr_t)(handle)) #define AS_BUFFER(handle) ((Buffer *)(uintptr_t)(handle)) #define AS_PIPELINE(handle) ((Pipeline *)(uintptr_t)(handle)) -#define AS_SURFACE(handle) ((GLSurface *)(uintptr_t)(handle)) +#define AS_SURFACE(handle) ((Surface *)(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)) @@ -828,13 +848,16 @@ pipeline_create( return GPU_NULL_HANDLE; } apply_bindings(p, bindings, num_bindings); + p->flip_y_location = glGetUniformLocation(p->id, "kitty_flip_y"); return AS_HANDLE(p); } static void -use_pipeline(void *driver UNUSED, gpu_pipeline_t pipeline) { - const Pipeline *p = AS_PIPELINE(pipeline); +use_pipeline(void *driver, gpu_pipeline_t pipeline) { + Driver *d = driver; + Pipeline *p = AS_PIPELINE(pipeline); glUseProgram(p ? p->id : 0); + d->current_pipeline = p; } static bool @@ -1073,33 +1096,46 @@ static gpu_surface_t surface_create(void *driver, const GPUNativeWindow *native, const GPUSurfaceConfig *config, uint32_t width, uint32_t height) { Driver *d = driver; if (!ensure_platform(d, native->platform)) return GPU_NULL_HANDLE; - GLSurface *s = d->platform->surface_create(native, config, width, height); - if (s) host_debug("Created %s OpenGL context for window of size: %ux%u", d->platform->name, width, height); + Surface *s = calloc(1, sizeof(Surface)); + if (!s) { + set_error(d, "Out of memory allocating a surface"); + return GPU_NULL_HANDLE; + } + if (!(s->gl = d->platform->surface_create(native, config, width, height))) { + free(s); + return GPU_NULL_HANDLE; + } + s->width = width; + s->height = height; + host_debug("Created %s OpenGL context for window of size: %ux%u", d->platform->name, width, height); return AS_HANDLE(s); } static void surface_destroy(void *driver, gpu_surface_t surface) { Driver *d = driver; - GLSurface *s = AS_SURFACE(surface); + Surface *s = AS_SURFACE(surface); if (!s || !d->platform) return; if (d->current_surface == s) { d->platform->make_current(NULL); d->current_surface = NULL; + d->current_pipeline = NULL; } - d->platform->surface_destroy(s); + d->platform->surface_destroy(s->gl); + free(s); } static bool make_surface_current(void *driver, gpu_surface_t surface) { Driver *d = driver; - GLSurface *s = AS_SURFACE(surface); + Surface *s = AS_SURFACE(surface); if (!d->platform) { if (!s) return true; set_error(d, "Cannot make a surface current before any surface is created"); return false; } - if (!d->platform->make_current(s)) return false; + if (!d->platform->make_current(s ? s->gl : NULL)) return false; + if (d->current_surface != s) d->current_pipeline = NULL; // the current program is per context d->current_surface = s; return true; } @@ -1112,34 +1148,40 @@ get_current_surface(void *driver) { static void surface_resize(void *driver, gpu_surface_t surface, uint32_t width, uint32_t height) { Driver *d = driver; - if (surface && d->platform) d->platform->surface_resize(AS_SURFACE(surface), width, height); + Surface *s = AS_SURFACE(surface); + if (!s || !d->platform) return; + s->width = width; + s->height = height; + d->platform->surface_resize(s->gl, width, height); } static bool surface_present(void *driver, gpu_surface_t surface) { Driver *d = driver; if (!surface || !d->platform) return false; - return d->platform->present(AS_SURFACE(surface)); + return d->platform->present(AS_SURFACE(surface)->gl); } static void surface_set_swap_interval(void *driver, gpu_surface_t surface, int interval) { Driver *d = driver; - if (surface && d->platform) d->platform->set_swap_interval(AS_SURFACE(surface), interval); + if (surface && d->platform) d->platform->set_swap_interval(AS_SURFACE(surface)->gl, interval); } static void surface_native_changed(void *driver, gpu_surface_t surface) { Driver *d = driver; - if (surface && d->platform) d->platform->native_changed(AS_SURFACE(surface)); + if (surface && d->platform) d->platform->native_changed(AS_SURFACE(surface)->gl); } static bool surface_recreate(void *driver, gpu_surface_t surface) { Driver *d = driver; if (!surface || !d->platform) return false; - if (!d->platform->recreate(AS_SURFACE(surface))) return false; + if (!d->platform->recreate(AS_SURFACE(surface)->gl)) return false; d->current_surface = AS_SURFACE(surface); + d->current_surface->render_target = 0; + d->current_pipeline = NULL; return true; } @@ -1149,6 +1191,7 @@ release_native_resources(void *driver) { if (!d->platform) return; d->platform->make_current(NULL); d->current_surface = NULL; + d->current_pipeline = NULL; d->platform->terminate(); d->platform = NULL; } @@ -1201,14 +1244,48 @@ render_target_create(void *driver UNUSED, gpu_texture_t color_texture) { } static void -render_target_destroy(void *driver UNUSED, gpu_render_target_t target) { +render_target_destroy(void *driver, gpu_render_target_t target) { + Driver *d = driver; GLuint fbo = AS_GL_NAME(target); - if (fbo) glDeleteFramebuffers(1, &fbo); + if (!fbo) return; + glDeleteFramebuffers(1, &fbo); + // Deleting a bound framebuffer object binds the window framebuffer + if (d->current_surface && d->current_surface->render_target == fbo) d->current_surface->render_target = 0; +} + +// The height of the window framebuffer if the window is the current render +// target, see Surface, otherwise zero +static uint32_t +window_height(const Driver *d) { + const Surface *s = d->current_surface; + return s && !s->render_target ? s->height : 0; +} + +// Convert the y co-ordinate of a rectangle between the top left origin of +// the API and the bottom left origin of OpenGL window framebuffers. The +// conversion is its own inverse. window_height is from window_height(). +static int32_t +convert_y(uint32_t window_height, int32_t y, uint32_t height) { + return window_height ? (int32_t)window_height - y - (int32_t)height : y; } static void -set_render_target(void *driver UNUSED, gpu_render_target_t target) { +set_render_target(void *driver, gpu_render_target_t target) { + // The viewport and scissor rectangle are relative to the top left of the + // render target, so must be converted when switching between a window + // and a framebuffer object + const uint32_t before = window_height(driver); + GLint vp[4], sc[4]; + glGetIntegerv(GL_VIEWPORT, vp); + glGetIntegerv(GL_SCISSOR_BOX, sc); glBindFramebuffer(GL_FRAMEBUFFER, AS_GL_NAME(target)); + Driver *d = driver; + if (d->current_surface) d->current_surface->render_target = AS_GL_NAME(target); + const uint32_t after = window_height(driver); + if (before != after) { + glViewport(vp[0], convert_y(after, convert_y(before, vp[1], vp[3]), vp[3]), vp[2], vp[3]); + glScissor(sc[0], convert_y(after, convert_y(before, sc[1], sc[3]), sc[3]), sc[2], sc[3]); + } } static gpu_render_target_t @@ -1236,20 +1313,21 @@ clear(void *driver UNUSED, float r, float g, float b, float a) { } static void -set_viewport(void *driver UNUSED, int32_t x, int32_t y, uint32_t width, uint32_t height) { - glViewport(x, y, width, height); +set_viewport(void *driver, int32_t x, int32_t y, uint32_t width, uint32_t height) { + glViewport(x, convert_y(window_height(driver), y, height), width, height); } static void -get_viewport(void *driver UNUSED, int32_t ans[4]) { +get_viewport(void *driver, int32_t ans[4]) { glGetIntegerv(GL_VIEWPORT, ans); + ans[1] = convert_y(window_height(driver), ans[1], (uint32_t)ans[3]); } static void -set_scissor(void *driver UNUSED, bool enabled, int32_t x, int32_t y, uint32_t width, uint32_t height) { +set_scissor(void *driver, 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); + glScissor(x, convert_y(window_height(driver), y, height), width, height); } else glDisable(GL_SCISSOR_TEST); } @@ -1260,23 +1338,70 @@ set_srgb_output(void *driver UNUSED, bool enabled) { } static void -read_pixels(void *driver UNUSED, int32_t x, int32_t y, uint32_t width, uint32_t height, void *dst) { +read_pixels(void *driver, int32_t x, int32_t y, uint32_t width, uint32_t height, void *dst) { + const uint32_t wh = window_height(driver); glPixelStorei(GL_PACK_ALIGNMENT, 1); - glReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, dst); + glReadPixels(x, convert_y(wh, y, height), width, height, GL_RGBA, GL_UNSIGNED_BYTE, dst); glPixelStorei(GL_PACK_ALIGNMENT, 4); + if (wh && height > 1) { + // Window framebuffer rows are read bottom to top, reverse them + const size_t stride = 4u * (size_t)width; + uint8_t row[4096], *top = dst, *bottom = (uint8_t *)dst + stride * (height - 1); + for (; top < bottom; top += stride, bottom -= stride) { + for (size_t done = 0; done < stride; done += sizeof(row)) { + const size_t n = stride - done < sizeof(row) ? stride - done : sizeof(row); + memcpy(row, top + done, n); + memcpy(top + done, bottom + done, n); + memcpy(bottom + done, row, n); + } + } + } } static void -copy_to_texture(void *driver UNUSED, gpu_texture_t dst, int32_t x, int32_t y, uint32_t width, uint32_t height) { +copy_to_texture(void *driver, 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); + const uint32_t wh = window_height(driver); + if (!wh) { + // The first row of the texture of a framebuffer object is at the origin, as in the API + bind_for_management(t); + glCopyTexSubImage2D(t->target, 0, 0, 0, x, y, width, height); + return; + } + // Copy from the window with a blit that flips the rows, so that the top + // of the rectangle ends up in the first row of the texture + SavedFramebuffers saved = save_framebuffers(); + const GLboolean srgb = glIsEnabled(GL_FRAMEBUFFER_SRGB), scissor = glIsEnabled(GL_SCISSOR_TEST); + glDisable(GL_FRAMEBUFFER_SRGB); // copy the stored values, without any conversion + glDisable(GL_SCISSOR_TEST); + GLuint fbo; + glGenFramebuffers(1, &fbo); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, t->id, 0); + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + const GLint sy = convert_y(wh, y, height); + glBlitFramebuffer(x, sy, x + (GLint)width, sy + (GLint)height, 0, (GLint)height, (GLint)width, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST); + restore_framebuffers(saved); + glDeleteFramebuffers(1, &fbo); + if (srgb) glEnable(GL_FRAMEBUFFER_SRGB); + if (scissor) glEnable(GL_SCISSOR_TEST); } // }}} // Drawing {{{ static void -draw_quad(void *driver UNUSED, uint32_t instance_count, GPUBlendMode blend) { +draw_quad(void *driver, uint32_t instance_count, GPUBlendMode blend) { + Driver *d = driver; + Pipeline *p = d->current_pipeline; + if (p && p->flip_y_location >= 0) { + // Shaders produce y co-ordinates for a top left origin, flip them for + // window framebuffers, which have a bottom left origin, see Surface + const GLfloat flip_y = window_height(d) ? -1.f : 1.f; + if (p->flip_y != flip_y) { + glUniform1f(p->flip_y_location, flip_y); + p->flip_y = flip_y; + } + } if (blend == GPU_BLEND_PREMULTIPLIED_ALPHA) { glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); diff --git a/kitty/cursor_trail.c b/kitty/cursor_trail.c index e2a4eae68..9bc78ad2b 100644 --- a/kitty/cursor_trail.c +++ b/kitty/cursor_trail.c @@ -20,22 +20,22 @@ update_cursor_trail_target(CursorTrail *ct, Window *w, ndc_coords g) { case CURSOR_BLOCK: case CURSOR_HOLLOW: case CURSOR_BEAM: - case CURSOR_UNDERLINE: left = g.xstart + WD.screen->cursor_render_info.x * g.dx; bottom = g.ystart - (WD.screen->cursor_render_info.y + 1) * g.dy; + case CURSOR_UNDERLINE: left = g.xstart + WD.screen->cursor_render_info.x * g.dx; bottom = g.ystart + (WD.screen->cursor_render_info.y + 1) * g.dy; default: break; } switch (WD.screen->cursor_render_info.shape) { case CURSOR_BLOCK: case CURSOR_HOLLOW: right = left + g.dx; - top = bottom + g.dy; + top = bottom - g.dy; break; case CURSOR_BEAM: right = left + g.dx / WD.screen->cell_size.width * OPT(cursor_beam_thickness); - top = bottom + g.dy; + top = bottom - g.dy; break; case CURSOR_UNDERLINE: right = left + g.dx; - top = bottom + g.dy / WD.screen->cell_size.height * OPT(cursor_underline_thickness); + top = bottom - g.dy / WD.screen->cell_size.height * OPT(cursor_underline_thickness); break; default: break; } diff --git a/kitty/gpu.c b/kitty/gpu.c index bb145b54a..1884b6de3 100644 --- a/kitty/gpu.c +++ b/kitty/gpu.c @@ -179,23 +179,13 @@ static struct { } saved_viewports; void -save_viewport_using_bottom_left_origin(int32_t newx, int32_t newy, uint32_t width, uint32_t height) { +save_viewport(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"); @@ -204,9 +194,8 @@ restore_viewport(void) { } 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); +enable_scissor(Viewport vp) { + gpu_set_scissor(true, vp.left, vp.top, vp.width, vp.height); } void @@ -287,7 +276,7 @@ save_texture_as_png(gpu_texture_t texture, const char *filename) { 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); + const char *png = png_from_32bit_rgba((char *)data, width, height, &sz, false); 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)); diff --git a/kitty/gpu.h b/kitty/gpu.h index 04f4b65c2..1c33c7ce4 100644 --- a/kitty/gpu.h +++ b/kitty/gpu.h @@ -346,10 +346,11 @@ typedef struct Viewport { } 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); +// Co-ordinates are relative to the top left corner of the render target, see gpu/api.h +// Set the viewport, saving the current one, which is restored by restore_viewport() +void save_viewport(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 enable_scissor(Viewport); void disable_scissor(void); // Draw a quad, blending pre-multiplied colors if blend is true void draw_quad(bool blend, unsigned instance_count); diff --git a/kitty/graphics.c b/kitty/graphics.c index 467e08967..de0ab78f2 100644 --- a/kitty/graphics.c +++ b/kitty/graphics.c @@ -1182,7 +1182,7 @@ finish_command_response(const GraphicsCommand *g, bool data_loaded) { static void update_src_rect(ImageRef *ref, Image *img) { - // The src rect in OpenGL co-ords [0, 1] with origin at top-left corner of image + // The src rect in texture co-ords [0, 1] with origin at top-left corner of image ref->src_rect.left = (float)ref->src_x / (float)img->width; ref->src_rect.right = (float)(ref->src_x + ref->src_width) / (float)img->width; ref->src_rect.top = (float)ref->src_y / (float)img->height; @@ -1551,7 +1551,7 @@ handle_put_command(GraphicsManager *self, const GraphicsCommand *g, Cursor *c, b void gpu_data_for_image(ImageRenderData *ans, float left, float top, float right, float bottom) { - // For dest rect: x-axis is from -1 to 1, y axis is from 1 to -1 + // For dest rect: x-axis is from -1 to 1, y axis is from -1 (top) to 1 (bottom) static const ImageRef source_rect = {.src_rect = {.left = 0, .top = 0, .bottom = 1, .right = 1}}; ans->src_rect = source_rect.src_rect; ans->dest_rect = (ImageRect){.left = left, .right = right, .top = top, .bottom = bottom}; @@ -1627,10 +1627,11 @@ grman_update_layers( self->num_of_indexed_refs = 0; ImageRect r; float screen_width = dx * num_cols, screen_height = dy * num_rows; - float screen_bottom = screen_top - screen_height; + // NDC y increases downwards, see gpu/api.h + float screen_bottom = screen_top + screen_height; float screen_width_px = num_cols * cell.width; float screen_height_px = num_rows * cell.height; - float y0 = screen_top - dy * ((float)scrolled_by + scroll_offset_lines); + float y0 = screen_top + dy * ((float)scrolled_by + scroll_offset_lines); // Iterate over all visible refs and create render data self->render_data.count = 0; @@ -1657,15 +1658,15 @@ grman_update_layers( continue; } } - r.top = y0 - start_row * dy - dy * (float)ref->cell_y_offset / (float)cell.height; + r.top = y0 + start_row * dy + dy * (float)ref->cell_y_offset / (float)cell.height; r.left = screen_left + start_column * dx + dx * (float)ref->cell_x_offset / (float)cell.width; int32_t nr = ref->num_rows, nc = ref->num_cols; if (nr) { - r.bottom = y0 - (start_row + nr) * dy; + r.bottom = y0 + (start_row + nr) * dy; if (nc) r.right = screen_left + (start_column + nc) * dx; else { - double height_px = (((double)r.top - r.bottom) / screen_height) * screen_height_px; + double height_px = (((double)r.bottom - r.top) / screen_height) * screen_height_px; double width_px = height_px * ref->src_width / (double)ref->src_height; r.right = r.left + (float)((width_px / screen_width_px) * screen_width); } @@ -1674,10 +1675,10 @@ grman_update_layers( else r.right = r.left + screen_width * (float)ref->src_width / screen_width_px; double width_px = (((double)r.right - r.left) / screen_width) * screen_width_px; double height_px = width_px * ref->src_height / (double)ref->src_width; - r.bottom = r.top - (float)((height_px / screen_height_px) * screen_height); + r.bottom = r.top + (float)((height_px / screen_height_px) * screen_height); } - if (r.top <= screen_bottom || r.bottom >= screen_top) { + if (r.top >= screen_bottom || r.bottom <= screen_top) { refitr = vt_next(refitr); continue; } // not visible @@ -1700,7 +1701,7 @@ grman_update_layers( self->num_of_indexed_refs++; // The rect is in normalized device co-ordinates, so allow for rounding errors const float width_px = (r.right - r.left) / screen_width * screen_width_px; - const float height_px = (r.top - r.bottom) / screen_height * screen_height_px; + const float height_px = (r.bottom - r.top) / screen_height * screen_height_px; rd->is_unscaled = fabsf(width_px - ref->src_width) < 0.01f && fabsf(height_px - ref->src_height) < 0.01f; } img->is_drawn = true; diff --git a/kitty/graphics.h b/kitty/graphics.h index 29dede82d..bc3634ff8 100644 --- a/kitty/graphics.h +++ b/kitty/graphics.h @@ -218,14 +218,9 @@ tex_pos_x(const int px_from_left_margin, const unsigned texture_width) { static inline float gl_pos_y(const int px_from_top_margin, const unsigned int viewport_size) { + // NDC y increases downwards from -1 at the top, see gpu/api.h const float px = 2.f / viewport_size; - return 1.f - px_from_top_margin * px; -} - -static inline float -tex_pos_y(const int px_from_top_margin, const unsigned texture_height) { - const int px_from_bottom_margin = texture_height - px_from_top_margin; - return px_from_bottom_margin / (float)texture_height; + return -1.f + px_from_top_margin * px; } diff --git a/kitty/rc/screenshot.py b/kitty/rc/screenshot.py index f8efa6d86..ef7849c29 100644 --- a/kitty/rc/screenshot.py +++ b/kitty/rc/screenshot.py @@ -104,7 +104,7 @@ class Screenshot(RemoteCommand): responder.send_error('Failed to take screenshot, the OS window may have been closed') return try: - png_data = png_from_32bit_rgba_data(pixels, width, height, True) + png_data = png_from_32bit_rgba_data(pixels, width, height) if output_path: with open(os.path.expanduser(output_path), 'wb') as f: f.write(png_data) diff --git a/kitty/screen.c b/kitty/screen.c index f8bd563f8..57f896c68 100644 --- a/kitty/screen.c +++ b/kitty/screen.c @@ -4733,7 +4733,7 @@ screen_update_graphics_layers(Screen *self) { rendered_scrolled_by(self), scroll_offset_lines_for_screen(self), -1.f, - 1.f, + -1.f, 2.f / self->columns, 2.f / self->lines, self->columns, diff --git a/kitty/shaders.c b/kitty/shaders.c index 6905911c4..8a952e9ee 100644 --- a/kitty/shaders.c +++ b/kitty/shaders.c @@ -336,7 +336,6 @@ thickness_as_float(const OSWindow *os_window, unsigned level) { static void draw_rounded_rect( Viewport rect, - unsigned framebuffer_height, float thickness, unsigned corner_radius_px, color_type srgb_color, @@ -348,11 +347,9 @@ draw_rounded_rect( color_vec4(program_param(ROUNDED_RECT_PROGRAM, "color"), srgb_color, 1.f); color_vec4(program_param(ROUNDED_RECT_PROGRAM, "background_color"), srgb_background, bg_alpha); color_vec4(program_param(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); - param_4f(program_param(ROUNDED_RECT_PROGRAM, "rect"), rect.left, y, rect.width, rect.height); + param_2f(program_param(ROUNDED_RECT_PROGRAM, "size"), rect.width, rect.height); param_2f(program_param(ROUNDED_RECT_PROGRAM, "params"), thickness, corner_radius_px); - save_viewport_using_top_left_origin(rect.left, rect.top, rect.width, rect.height, framebuffer_height); + save_viewport(rect.left, rect.top, rect.width, rect.height); draw_quad(true, 0); restore_viewport(); } @@ -1414,7 +1411,7 @@ draw_visual_bell_flash(float intensity, const color_type flash) { if (max_channel > 0.45) attenuation = 0.6f; // light color param_4f(program_param(TINT_PROGRAM, "tint_color"), C(r), C(g), C(b), C(1)); #undef C - param_4f(program_param(TINT_PROGRAM, "edges"), -1, 1, 1, -1); + param_4f(program_param(TINT_PROGRAM, "edges"), -1, -1, 1, 1); draw_quad(true, 0); } @@ -1447,7 +1444,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; - float 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 @@ -1548,7 +1545,7 @@ draw_bar(const UIRenderData *ui, const WindowBarData *bar, Viewport border_rect, // bleed onto the rendered title. 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); + gpu_data_for_image(&data, -1, -1, 1, 1); const GPUTextureDesc desc = { .kind = GPU_TEXTURE_2D, .format = GPU_FORMAT_SRGB8_ALPHA8, @@ -1559,18 +1556,17 @@ draw_bar(const UIRenderData *ui, const WindowBarData *bar, Viewport border_rect, 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 - enable_scissor_using_top_left_origin(border_rect, sh); + enable_scissor(border_rect); blank_canvas(ui->bg_alpha, bg, false); disable_scissor(); // then draw the rendered text - save_viewport_using_top_left_origin(border_rect.left + border_width, border_rect.top + border_width, bar->width, bar->height, sh); + save_viewport(border_rect.left + border_width, border_rect.top + border_width, bar->width, bar->height); draw_graphics(GRAPHICS_PROGRAM, &data, 0, 1, 1.f); restore_viewport(); free_texture(&data.texture_id); // finally draw border with transparent bg - draw_rounded_rect(border_rect, sh, drawn_thickness, ui->cell_width, fg, bg, 0.f, 0, 0.f); + draw_rounded_rect(border_rect, drawn_thickness, ui->cell_width, fg, bg, 0.f, 0, 0.f); } static unsigned @@ -1697,7 +1693,7 @@ draw_window_number(const UIRenderData *ui) { if (lr.height_px + title_bar_height < ui->screen_height) letter_y += (ui->screen_height - lr.height_px - title_bar_height) / 2; 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); + gpu_data_for_image(ird, -1, -1, 1, 1); color_type digit_color = colorprofile_to_color_with_fallback( ui->screen->color_profile, ui->screen->color_profile->overridden.highlight_bg, @@ -1706,7 +1702,7 @@ draw_window_number(const UIRenderData *ui) { ui->screen->color_profile->configured.default_fg); color_vec3(program_param(GRAPHICS_ALPHA_MASK_PROGRAM, "amask_fg"), digit_color); param_4f(program_param(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); + save_viewport(ui->screen_left + letter_x, ui->screen_top + letter_y, lr.width_px, lr.height_px); draw_graphics(GRAPHICS_ALPHA_MASK_PROGRAM, ird, 0, 1, 1.f); restore_viewport(); #undef lr @@ -1762,29 +1758,29 @@ draw_scrollbar(const UIRenderData *ui) { float min_thumb_height_fraction = (OPT(scrollbar_min_handle_height) * ui->cell_height) / (float)window_height; float thumb_height_fraction = MAX(min_thumb_height_fraction, visible_fraction); - // Convert to OpenGL coordinates (range -1.0 to 1.0, total span = 2.0) + // Convert to NDC (range -1.0 to 1.0, total span = 2.0, -1 is the top) const float GL_COORD_SPAN = 2.0f; float thumb_height_gl = thumb_height_fraction * GL_COORD_SPAN; float available_space = GL_COORD_SPAN - thumb_height_gl; - float thumb_bottom_gl = -1.0f + available_space * bar_frac; - float thumb_top_gl = thumb_bottom_gl + thumb_height_gl; + float thumb_bottom_gl = 1.0f - available_space * bar_frac; + float thumb_top_gl = thumb_bottom_gl - thumb_height_gl; // Store thumb position for mouse interaction (normalized window coordinates) float scrollbar_top_in_window = (float)(window_top_edge + scrollbar_gap_px) / (float)ui->full_framebuffer_height; float scrollbar_height_in_window = (float)(window_height - 2 * scrollbar_gap_px) / (float)ui->full_framebuffer_height; - float thumb_top_fraction = (1.0f - thumb_top_gl) / 2.0f; - float thumb_bottom_fraction = (1.0f - thumb_bottom_gl) / 2.0f; + float thumb_top_fraction = (1.0f + thumb_top_gl) / 2.0f; + float thumb_bottom_fraction = (1.0f + thumb_bottom_gl) / 2.0f; window->scrollbar.thumb_top = scrollbar_top_in_window + thumb_top_fraction * scrollbar_height_in_window; window->scrollbar.thumb_bottom = scrollbar_top_in_window + thumb_bottom_fraction * scrollbar_height_in_window; // Set viewport for scrollbar area - save_viewport_using_top_left_origin(scrollbar_left, scrollbar_top, scrollbar_width_px, scrollbar_height, ui->full_framebuffer_height); + save_viewport(scrollbar_left, scrollbar_top, scrollbar_width_px, scrollbar_height); // Draw scrollbar track (background) if (track_opacity > 0) { bind_program(TINT_PROGRAM); set_color_uniform_with_opacity(track_color, track_opacity); - param_4f(program_param(TINT_PROGRAM, "edges"), -1.f, 1.f, 1.f, -1.f); + param_4f(program_param(TINT_PROGRAM, "edges"), -1.f, -1.f, 1.f, 1.f); draw_quad(true, 0); } @@ -1801,13 +1797,12 @@ draw_scrollbar(const UIRenderData *ui) { color_vec4(program_param(ROUNDED_RECT_PROGRAM, "background_color"), 0, 0.0f); color_vec4(program_param(ROUNDED_RECT_PROGRAM, "outer_color"), 0, 0.0f); - float y = (float)ui->full_framebuffer_height - (float)(thumb_top_px + thumb_height_px); - param_4f(program_param(ROUNDED_RECT_PROGRAM, "rect"), (float)scrollbar_left, y, (float)scrollbar_width_px, (float)thumb_height_px); + param_2f(program_param(ROUNDED_RECT_PROGRAM, "size"), (float)scrollbar_width_px, (float)thumb_height_px); float thickness = (float)MAX(scrollbar_width_px, thumb_height_px); param_2f(program_param(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); + save_viewport(scrollbar_left, thumb_top_px, scrollbar_width_px, thumb_height_px); draw_quad(true, 0); restore_viewport(); } else { @@ -1826,7 +1821,6 @@ has_progress_bar(Screen *screen) { static void draw_progress_handle( - const UIRenderData *ui, color_type bar_color, float opacity, unsigned bar_radius, @@ -1868,13 +1862,12 @@ draw_progress_handle( color_vec4(program_param(ROUNDED_RECT_PROGRAM, "background_color"), 0, 0.0f); color_vec4(program_param(ROUNDED_RECT_PROGRAM, "outer_color"), 0, 0.0f); - float y = (float)ui->full_framebuffer_height - (float)(handle_top + handle_h); - param_4f(program_param(ROUNDED_RECT_PROGRAM, "rect"), (float)handle_left, y, (float)handle_w, (float)handle_h); + param_2f(program_param(ROUNDED_RECT_PROGRAM, "size"), (float)handle_w, (float)handle_h); float thickness = (float)(is_horizontal ? handle_h : handle_w); param_2f(program_param(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); + save_viewport(handle_left, handle_top, handle_w, handle_h); draw_quad(true, 0); restore_viewport(); } else { @@ -1888,12 +1881,12 @@ draw_progress_handle( set_color_uniform_with_opacity(bar_color, opacity); 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); - param_4f(program_param(TINT_PROGRAM, "edges"), start_gl, 1.f, end_gl, -1.f); + save_viewport(track_left, track_top, track_width, track_height); + param_4f(program_param(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 - param_4f(program_param(TINT_PROGRAM, "edges"), -1.f, -start_gl, 1.f, -end_gl); + save_viewport(track_left, track_top, track_width, track_height); + // For vertical: the handle moves top to bottom, as NDC y does + param_4f(program_param(TINT_PROGRAM, "edges"), -1.f, start_gl, 1.f, end_gl); } draw_quad(true, 0); restore_viewport(); @@ -1966,11 +1959,11 @@ draw_progress_bar(const UIRenderData *ui) { } // Draw track (background) - save_viewport_using_top_left_origin(track_left, track_top, track_width, track_height, ui->full_framebuffer_height); + save_viewport(track_left, track_top, track_width, track_height); if (track_opacity > 0) { bind_program(TINT_PROGRAM); set_color_uniform_with_opacity(track_color, track_opacity); - param_4f(program_param(TINT_PROGRAM, "edges"), -1.f, 1.f, 1.f, -1.f); + param_4f(program_param(TINT_PROGRAM, "edges"), -1.f, -1.f, 1.f, 1.f); draw_quad(true, 0); } restore_viewport(); @@ -1988,12 +1981,11 @@ draw_progress_bar(const UIRenderData *ui) { if (!is_horizontal) pos_frac = 1.0f - pos_frac; // vertical: bounce bottom-to-top first float handle_start = pos_frac * (1.0f - handle_size); if (opacity > 0.0f) { - draw_progress_handle( - ui, bar_color, opacity, bar_radius, track_left, track_top, track_width, track_height, handle_start, handle_size, is_horizontal); + draw_progress_handle(bar_color, opacity, bar_radius, track_left, track_top, track_width, track_height, handle_start, handle_size, is_horizontal); } } else if (fill_fraction > 0.0f && opacity > 0.0f) { float handle_start = is_horizontal ? 0.0f : 1.0f - fill_fraction; - draw_progress_handle(ui, bar_color, opacity, bar_radius, track_left, track_top, track_width, track_height, handle_start, fill_fraction, is_horizontal); + draw_progress_handle(bar_color, opacity, bar_radius, track_left, track_top, track_width, track_height, handle_start, fill_fraction, is_horizontal); } } @@ -2042,7 +2034,7 @@ draw_window_logo(const UIRenderData *ui) { w.top = (int)(ui->screen_height * wl->position.canvas_y - w.height * wl->position.image_y); float left = gl_pos_x(w.left, ui->screen_width), top = gl_pos_y(w.top, ui->screen_height); ImageRenderData d = {.texture_id = wl->instance->texture_id}; - gpu_data_for_image(&d, left, top, left + gl_size(w.width, ui->screen_width), top - gl_size(w.height, ui->screen_height)); + gpu_data_for_image(&d, left, top, left + gl_size(w.width, ui->screen_width), top + gl_size(w.height, ui->screen_height)); draw_graphics(GRAPHICS_PROGRAM, &d, 0, 1, ui->inactive_text_alpha * OPT(window_logo_alpha)); } @@ -2154,7 +2146,7 @@ draw_window_padding(const UIRenderData *ui, unsigned int cl, unsigned int ct, un const float fL = (float)ui->screen_left, T = (float)ui->screen_top; const float R = fL + (float)ui->screen_width, B = T + (float)ui->screen_height; #define NX(px) (2.f * (px) / fbw - 1.f) -#define NY(px) (1.f - 2.f * (px) / fbh) +#define NY(px) (2.f * (px) / fbh - 1.f) const float dx = 2.f * cw / fbw, dy = 2.f * ch / fbh; bind_program(PADDING_PROGRAM); @@ -2273,7 +2265,7 @@ draw_window_padding(const UIRenderData *ui, unsigned int cl, unsigned int ct, un param_2f(PL(across), cl ? NX(fL - cl) : NX(R), cl ? NX(fL) : NX(R + cr)); param_2f(PL(across2), NX(R), NX(R + cr)); param_1f(PL(along_start), NY(T)); - param_1f(PL(along_step), -dy); + param_1f(PL(along_step), dy); param_2f(PL(along_clamp), NY(T - ct), NY(B + cb)); draw_quad(!for_final_output, nV * lines); } @@ -2291,7 +2283,7 @@ static void draw_tint(const UIRenderData *ui) { bind_program(TINT_PROGRAM); color_vec4_premult(program_param(TINT_PROGRAM, "tint_color"), ui->background_color, OPT(background_tint)); - param_4f(program_param(TINT_PROGRAM, "edges"), -1, 1, 1, -1); + param_4f(program_param(TINT_PROGRAM, "edges"), -1, -1, 1, 1); draw_quad(true, 0); } @@ -2425,7 +2417,7 @@ draw_cells( .now = now, }; screen->reload_all_gpu_data = false; - save_viewport_using_top_left_origin(ui.screen_left, ui.screen_top, ui.screen_width, ui.screen_height, ui.full_framebuffer_height); + save_viewport(ui.screen_left, ui.screen_top, ui.screen_width, ui.screen_height); if (ui.os_window->needs_layers) draw_cells_with_layers(&ui, srd->vao_idx); else draw_cells_without_layers(&ui, srd->vao_idx); restore_viewport(); @@ -2547,7 +2539,7 @@ draw_rounded_borders(BorderRects *br, color_type active_window_bg, unsigned int unsigned radius = MIN(r->radius, MIN(rect.width, rect.height) / 2); unsigned color_index = r->color & 0xff; 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); + draw_rounded_rect(rect, (float)r->thickness, radius, color, 0, 0.f, colors[0], corner_bg_alpha); } if (!w->needs_layers) gpu_set_srgb_output(false); unbind_program(); @@ -2612,7 +2604,7 @@ draw_bg_image(OSWindow *os_window, Tab *tab) { } float tiled = 0.f; ; - float 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: @@ -2624,8 +2616,8 @@ draw_bg_image(OSWindow *os_window, Tab *tab) { float hfrac = (vheight - iheight) / vheight; left += wfrac; right -= wfrac; - top -= hfrac; - bottom += hfrac; + top += hfrac; + bottom -= hfrac; } break; } bind_program(BGIMAGE_PROGRAM); @@ -2645,7 +2637,7 @@ gpu_data_for_centered_image(ImageRenderData *ans, unsigned int screen_width_px, float width_frac = 2 * MIN(1, width / (float)screen_width_px), height_frac = 2 * MIN(1, height / (float)screen_height_px); float hmargin = (2 - width_frac) / 2; float vmargin = (2 - height_frac) / 2; - gpu_data_for_image(ans, -1 + hmargin, 1 - vmargin, -1 + hmargin + width_frac, 1 - vmargin - height_frac); + gpu_data_for_image(ans, -1 + hmargin, -1 + vmargin, -1 + hmargin + width_frac, -1 + vmargin + height_frac); } static void @@ -2790,7 +2782,7 @@ start_os_window_rendering(OSWindow *os_window, Tab *tab) { } set_framebuffer_to_use_for_output(os_window->indirect_output.framebuffer_id); bind_framebuffer_for_output(0); - save_viewport_using_bottom_left_origin(0, 0, os_window->viewport_width, os_window->viewport_height); + save_viewport(0, 0, os_window->viewport_width, os_window->viewport_height); clear_current_framebuffer(); draw_bg_image(os_window, tab); } @@ -2884,11 +2876,17 @@ update_pointer_map(OSWindow *os_window, int32_t group_loc) { draw_quad(false, 0); static uint8_t pixels[POINTER_MAP_SIZE * POINTER_MAP_SIZE * 4]; 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; - os_window->pointer_map.data[2 * i] = (float)(p[0] * 256 + p[2]) / 65535.f; - os_window->pointer_map.data[2 * i + 1] = (float)(p[1] * 256 + p[3]) / 65535.f; + // See encode_pointer_map() in pipeline.slang. Rows are read back top to + // bottom, while rows of the pointer map are in order of increasing UV y, + // that is, bottom to top. + for (size_t row = 0; row < POINTER_MAP_SIZE; row++) { + const uint8_t *src = pixels + 4 * POINTER_MAP_SIZE * row; + float *dst = os_window->pointer_map.data + 2 * POINTER_MAP_SIZE * (POINTER_MAP_SIZE - 1 - row); + for (size_t col = 0; col < POINTER_MAP_SIZE; col++) { + const uint8_t *p = src + 4 * col; + dst[2 * col] = (float)(p[0] * 256 + p[2]) / 65535.f; + dst[2 * col + 1] = (float)(p[1] * 256 + p[3]) / 65535.f; + } } os_window->pointer_map.groups = groups; } @@ -2954,12 +2952,13 @@ run_custom_end_shader(OSWindow *os_window, float sx, float sy, monotonic_t now) } struct GPUCustomEndData *d = (struct GPUCustomEndData *)map_vao_buffer_for_write_only(custom_end_vao_idx, 0, 0, data_block.size); memset(d, 0, sizeof(struct GPUCustomEndData)); - d->src_rect[1] = sy; + // The viewport is in the top left corner of the texture, see gpu/api.h d->src_rect[2] = sx; + d->src_rect[3] = sy; d->dest_rect[0] = -1; - d->dest_rect[1] = 1; + d->dest_rect[1] = -1; d->dest_rect[2] = 1; - d->dest_rect[3] = -1; + d->dest_rect[3] = 1; #define FILL_COLOR(dst, c) \ do { \ (dst)[0] = srgb_color(((c) >> 16) & 0xFF); \ @@ -3016,7 +3015,9 @@ run_custom_end_shader(OSWindow *os_window, float sx, float sy, monotonic_t now) } FILL_COLOR(d->active_window_background, active_bg); #undef FILL_COLOR + // NDC y increases downwards while UV y, as seen by custom shaders, increases upwards #define NDC_TO_UV(v) (((v) + 1.0f) * 0.5f) +#define NDC_Y_TO_UV(v) ((1.0f - (v)) * 0.5f) // Convert to seconds via double, as float32 cannot represent times since // kitty started precisely once kitty has been running for a few hours. #define SECONDS(t) ((float)monotonic_t_to_s_double(t)) @@ -3033,9 +3034,9 @@ run_custom_end_shader(OSWindow *os_window, float sx, float sy, monotonic_t now) if (!m->at) break; for (int k = 0; k < 2; k++) { d->cursor_trail_history_from[i][k] = NDC_TO_UV(m->from_x[k]); - d->cursor_trail_history_from[i][k + 2] = NDC_TO_UV(m->from_y[k]); + d->cursor_trail_history_from[i][k + 2] = NDC_Y_TO_UV(m->from_y[k]); d->cursor_trail_history_to[i][k] = NDC_TO_UV(m->to_x[k]); - d->cursor_trail_history_to[i][k + 2] = NDC_TO_UV(m->to_y[k]); + d->cursor_trail_history_to[i][k + 2] = NDC_Y_TO_UV(m->to_y[k]); } d->cursor_trail_history_age[i / 4][i % 4] = SECONDS(now - m->at); } @@ -3043,19 +3044,19 @@ run_custom_end_shader(OSWindow *os_window, float sx, float sy, monotonic_t now) if (ct) { for (int i = 0; i < 4; i++) { d->cursor_trail_corners_x[i] = NDC_TO_UV(ct->corner_x[i]); - d->cursor_trail_corners_y[i] = NDC_TO_UV(ct->corner_y[i]); + d->cursor_trail_corners_y[i] = NDC_Y_TO_UV(ct->corner_y[i]); d->cursor_trail_prev_corners_x[i] = NDC_TO_UV(ct->previous_corner_x[i]); - d->cursor_trail_prev_corners_y[i] = NDC_TO_UV(ct->previous_corner_y[i]); + d->cursor_trail_prev_corners_y[i] = NDC_Y_TO_UV(ct->previous_corner_y[i]); } - d->cursor_trail_edge[0] = NDC_TO_UV(ct->cursor_edge_x[0]); // left - d->cursor_trail_edge[1] = NDC_TO_UV(ct->cursor_edge_x[1]); // right - d->cursor_trail_edge[2] = NDC_TO_UV(ct->cursor_edge_y[0]); // top - d->cursor_trail_edge[3] = NDC_TO_UV(ct->cursor_edge_y[1]); // bottom + d->cursor_trail_edge[0] = NDC_TO_UV(ct->cursor_edge_x[0]); // left + d->cursor_trail_edge[1] = NDC_TO_UV(ct->cursor_edge_x[1]); // right + d->cursor_trail_edge[2] = NDC_Y_TO_UV(ct->cursor_edge_y[0]); // top + d->cursor_trail_edge[3] = NDC_Y_TO_UV(ct->cursor_edge_y[1]); // bottom if (ct->prev_edge_valid) { - d->cursor_trail_prev_edge[0] = NDC_TO_UV(ct->prev_cursor_edge_x[0]); // left - d->cursor_trail_prev_edge[1] = NDC_TO_UV(ct->prev_cursor_edge_x[1]); // right - d->cursor_trail_prev_edge[2] = NDC_TO_UV(ct->prev_cursor_edge_y[0]); // top - d->cursor_trail_prev_edge[3] = NDC_TO_UV(ct->prev_cursor_edge_y[1]); // bottom + d->cursor_trail_prev_edge[0] = NDC_TO_UV(ct->prev_cursor_edge_x[0]); // left + d->cursor_trail_prev_edge[1] = NDC_TO_UV(ct->prev_cursor_edge_x[1]); // right + d->cursor_trail_prev_edge[2] = NDC_Y_TO_UV(ct->prev_cursor_edge_y[0]); // top + d->cursor_trail_prev_edge[3] = NDC_Y_TO_UV(ct->prev_cursor_edge_y[1]); // bottom } d->cursor_trail_color[3] = ct->opacity; d->cursor_trail_state = 1.0f; @@ -3066,6 +3067,7 @@ run_custom_end_shader(OSWindow *os_window, float sx, float sy, monotonic_t now) } } #undef NDC_TO_UV +#undef NDC_Y_TO_UV #define FILL_COLOR3(dst, c) \ do { \ (dst)[0] = srgb_color(((c) >> 16) & 0xFF); \ @@ -3237,7 +3239,7 @@ 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) { - gpu_set_viewport(0, os_window->live_resize.height - vh, vw, vh); + gpu_set_viewport(0, 0, vw, vh); // the top left corner of the larger framebuffer } else { gpu_set_viewport(0, 0, vw, vh); } @@ -3249,12 +3251,12 @@ run_custom_end_shader(OSWindow *os_window, float sx, float sy, monotonic_t now) float px = cg->viewport_pos.x, py = cg->viewport_pos.y; 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. + // upward), while the GPU viewport has its origin at the top left. int32_t x0 = MAX(0, (int32_t)(px * vw)); - int32_t y0 = MAX(0, (int32_t)(py * vh)); + int32_t y0 = MAX(0, (int32_t)(py * vh)); // from the bottom 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)); + int32_t y1 = MIN(vh, (int32_t)((py + sh) * vh)); // from the bottom + gpu_set_viewport(x0, vh - y1, MAX(0, x1 - x0), MAX(0, y1 - y0)); vp_x = px; vp_y = py; vp_w = sw; @@ -3280,8 +3282,7 @@ stop_os_window_rendering(OSWindow *os_window, Tab *tab, Window *active_window, m if (custom_shaders.end.active && os_window->shader_anim.has_active_shaders) { // debug_rendering("Custom end shader running (groups=%zu)\n", custom_shaders.end.num_groups); 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); + if (os_window->live_resize.in_progress) save_viewport(0, 0, os_window->viewport_width, os_window->viewport_height); run_custom_end_shader(os_window, sx, sy, now); } else { // debug_rendering("Custom shaders inactive, falling back to blit\n"); @@ -3289,11 +3290,10 @@ stop_os_window_rendering(OSWindow *os_window, Tab *tab, Window *active_window, m bind_framebuffer_for_output(0); bind_program(BLIT_PROGRAM); gpu_bind_texture(program_texture_slot(BLIT_PROGRAM, "image"), global_state.layers_render_texture.texture_id); - param_4f(program_param(BLIT_PROGRAM, "src_rect"), 0, sy, sx, 0); - param_4f(program_param(BLIT_PROGRAM, "dest_rect"), -1, 1, 1, -1); + param_4f(program_param(BLIT_PROGRAM, "src_rect"), 0, 0, sx, sy); + param_4f(program_param(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); + if (os_window->live_resize.in_progress) save_viewport(0, 0, os_window->viewport_width, os_window->viewport_height); draw_quad(false, 0); } if (os_window->live_resize.in_progress) { @@ -3322,8 +3322,7 @@ setup_os_window_for_rendering(OSWindow *os_window, Tab *tab, Window *active_wind // Setting the thumbnail dimensions to zero disables scaling. // If no_scaling is true, thumb_w/thumb_h are ignored and the region is read // back directly from the framebuffer with no GPU resampling, for a pixel -// perfect capture (the output is in GL's native bottom-up row order, unlike -// the scaled path below which flips to top-down). +// perfect capture. In both cases rows are output top to bottom. void take_screenshot_of_rectangular_region(OSWindow *os_window, Region region, unsigned char *dst_buf, unsigned *thumb_w, unsigned *thumb_h, bool no_scaling) { unsigned vh = os_window->viewport_height; @@ -3335,7 +3334,7 @@ take_screenshot_of_rectangular_region(OSWindow *os_window, Region region, unsign if (no_scaling) { *thumb_w = src_width; *thumb_h = src_height; - gpu_read_pixels((int32_t)region.left, (int32_t)(vh - region.bottom), src_width, src_height, dst_buf); + gpu_read_pixels((int32_t)region.left, (int32_t)region.top, src_width, src_height, dst_buf); return; } @@ -3363,18 +3362,16 @@ take_screenshot_of_rectangular_region(OSWindow *os_window, Region region, unsign // Bind our temporary framebuffer for rendering bind_framebuffer_for_output(temp_framebuffer); - save_viewport_using_bottom_left_origin(0, 0, *thumb_w, *thumb_h); + save_viewport(0, 0, *thumb_w, *thumb_h); // Use the screenshot program to render the scaled framebuffer with proper color space handling bind_program(SCREENSHOT_PROGRAM); - // Set source rectangle (normalized coordinates: 0 to 1) - // Note: OpenGL texture origin is bottom-left, but Region uses top-left origin - // Convert from screen coordinates (top-left origin) to OpenGL texture coordinates (bottom-left origin) + // Set source rectangle (normalized texture coordinates: 0 to 1, origin at top-left, like Region) float src_left_norm = (float)region.left / (float)vw; 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; + float src_bottom_norm = (float)region.bottom / (float)vh; + float src_top_norm = (float)region.top / (float)vh; param_4f(program_param(SCREENSHOT_PROGRAM, "src_rect"), src_left_norm, src_top_norm, src_right_norm, src_bottom_norm); // Set destination rectangle (NDC coordinates: -1 to 1) diff --git a/kitty/shaders/background.slang b/kitty/shaders/background.slang index 633c439e6..3fad2afec 100644 --- a/kitty/shaders/background.slang +++ b/kitty/shaders/background.slang @@ -289,14 +289,15 @@ compute_background(uint3 colors, uint2 sprite_idx, uint is_selected, uint instan uint row = instance_id / crd.columns; uint column = instance_id - row * crd.columns; - // The position of this vertex, at a corner of the cell + // The position of this vertex, at a corner of the cell. NDC y increases + // downwards from -1 at the top. float left = -1.0 + float(column) * dx; - float top = 1.0 - (float(row) + crd.row_offset) * dy; + float top = -1.0 + (float(row) + crd.row_offset) * dy; uint2 pos = cell_pos_map[vertex_id]; float2 select_x = float2(left, left + dx); - float2 select_y = float2(top, top - dy); + float2 select_y = float2(top, top + dy); bo.position = float4(select_x[pos.x], select_y[pos.y], 0.0, 1.0); // }}} diff --git a/kitty/shaders/custom/pipeline.slang b/kitty/shaders/custom/pipeline.slang index 0dc63617c..29e8ba462 100644 --- a/kitty/shaders/custom/pipeline.slang +++ b/kitty/shaders/custom/pipeline.slang @@ -98,16 +98,20 @@ public float4 pipeline_fragment_main(float2 backbuffer_pos, int group, float4 viewport, float animation_progress, bool convert_to_srgb, uint active_groups) { float4 color = backbuffer.Sample(backbuffer_pos); // pre multiplied linear RGB color = float4(color.rgb / color.a, color.a); // un pre multiplied color passed through pipeline - // src_rect encodes (0, sy, sx, 0) — the fraction of the shared texture occupied by the current - // viewport. The shared texture is grown to fit the largest OS Window viewport and never - // shrunk, so sx/sy are less than one whenever this window is smaller than that. Normalize - // backbuffer_pos so that t.pos is always in [0,1] viewport UV and wrap the samplers so that - // shaders can address them in that same space, regardless of the size of the shared texture. - float2 src_scale = float2(max(1e-6, csd.src_rect[right]), max(1e-6, csd.src_rect[top])); - float2 viewport_pos = backbuffer_pos / src_scale; + // src_rect encodes (0, 0, sx, sy) — the fraction of the shared texture occupied by the current + // viewport, which is in its top left corner. The shared texture is grown to fit the largest + // OS Window viewport and never shrunk, so sx/sy are less than one whenever this window is + // smaller than that. Normalize backbuffer_pos so that t.pos is always in [0,1] viewport UV, + // which has its origin at the bottom left, unlike texture co-ordinates, and wrap the samplers + // so that shaders can address them in that same space, regardless of the size of the shared + // texture. + float2 src_scale = float2(max(1e-6, csd.src_rect[right]), max(1e-6, csd.src_rect[bottom])); + float2 tex_pos = backbuffer_pos / src_scale; + float2 viewport_pos = float2(tex_pos.x, 1.f - tex_pos.y); if (group < 0) return encode_pointer_map(viewport_pos, active_groups); - // Half a texel inset, in viewport UV, so that clamped samples do not bilinearly blend in the - // stale texels that lie just outside the viewport region of the shared texture. + // Half a texel inset, in normalized texture co-ordinates, so that clamped samples do not + // bilinearly blend in the stale texels that lie just outside the viewport region of the + // shared texture. float2 max_pos = 1.f - 0.5f / max(float2(csd.viewport_size_pixels), float2(1.f)); KittyTextures t = { { backbuffer, src_scale, max_pos }, diff --git a/kitty/shaders/custom/types.slang b/kitty/shaders/custom/types.slang index 1be4f1ef5..ff5751b8a 100644 --- a/kitty/shaders/custom/types.slang +++ b/kitty/shaders/custom/types.slang @@ -135,18 +135,20 @@ public struct KittyCustomShaderData { // A texture kitty renders into, addressed in the same UV co-ordinate space as // KittyTextures.pos. kitty renders into textures that are at least as large as // the largest OS Window viewport, so the pixels for the current OS Window -// occupy only the lower-left corner of the texture after the window is made -// smaller. Sampling via the Sample() method below hides that detail, so -// shaders never need to know the size of the underlying texture. +// occupy only the top-left corner of the texture after the window is made +// smaller. Also, texture co-ordinates have their origin at the top-left, +// unlike UV co-ordinates. Sampling via the Sample() method below hides these +// details, so shaders never need to know about the underlying texture. public struct KittyTexture { - // The underlying texture. Use this only if you need raw texture UV, - // remember to multiply your co-ordinates by scale below when you do. + // The underlying texture. Use this only if you need raw texture + // co-ordinates, which have their origin at the top-left, remember to + // multiply your co-ordinates by scale below when you do. public Sampler2D tex; // The fraction of tex occupied by the OS Window viewport. Always in (0, 1]. public float2 scale; - // The largest usable co-ordinate for Sample() below. Half a texel less than - // one, so that sampling the top/right edge does not blend in texels from - // outside the viewport. + // The largest usable texture co-ordinate, before multiplying by scale, + // for Sample() below. Half a texel less than one, so that sampling the + // right/bottom edge does not blend in texels from outside the viewport. public float2 max_pos; // Sample this texture at pos, which is in the same UV co-ordinate space as @@ -154,7 +156,7 @@ public struct KittyTexture { // Co-ordinates outside that range are clamped to the edge of the viewport. public float4 Sample(float2 pos) { - return tex.Sample(clamp(pos, float2(0.f), max_pos) * scale); + return tex.Sample(clamp(float2(pos.x, 1.f - pos.y), float2(0.f), max_pos) * scale); } } diff --git a/kitty/shaders/padding.slang b/kitty/shaders/padding.slang index 4c9bca58f..b8c557921 100644 --- a/kitty/shaders/padding.slang +++ b/kitty/shaders/padding.slang @@ -43,8 +43,7 @@ struct Params { // The two NDC values of the thin (across) dimension for strip 0. float2 across; // NDC of the along dimension for the first cell's near corner, and the step - // per cell (signed; negative for the vertical strips as NDC y decreases - // downwards). + // per cell (positive, as NDC x increases rightwards and NDC y downwards). float along_start; float along_step; // NDC bounds used to extend the first/last cell so the strip fills the diff --git a/kitty/shaders/rounded_rect.slang b/kitty/shaders/rounded_rect.slang index b262521c2..ae97fd44b 100644 --- a/kitty/shaders/rounded_rect.slang +++ b/kitty/shaders/rounded_rect.slang @@ -19,7 +19,7 @@ static const float2 vertex_pos_map[4] = { float2(1, 1), float2(1, -1), float2(-1 // The uniform parameters of the program, shared by all its stages. See // PUSH_CONSTANTS_MAX_SIZE in slang.py for why they are declared this way. struct Params { - float4 rect; + float2 size; // of the rectangle in pixels, the viewport is the rectangle float2 params; float4 color; float4 background_color; @@ -28,11 +28,18 @@ struct Params { [[vk::push_constant]] ConstantBuffer uniforms; +struct VertexOutput { + // Position within the rectangle, (0, 0) at one corner and (1, 1) at the + // opposite one. The shape is symmetric so which corner does not matter. + float2 uv : TEXCOORD; + float4 position : SV_Position; +}; + [shader("vertex")] -float4 -vertex_main(uint vertex_id: SV_VertexID) - : SV_Position { - return float4(vertex_pos_map[vertex_id], 0, 1); +VertexOutput +vertex_main(uint vertex_id: SV_VertexID) { + float2 pos = vertex_pos_map[vertex_id]; + return { pos * 0.5 + 0.5, float4(pos, 0, 1) }; } // Signed distance function for a rounded rectangle @@ -46,18 +53,15 @@ rounded_rectangle_sdf(float2 p, float2 b, float r) { [shader("fragment")] float4 -fragment_main( - float4 frag_coord: SV_Position // SV_Position provides gl_FragCoord equivalent in Slang - ) +fragment_main(float2 uv: TEXCOORD) : SV_Target { - float2 size = uniforms.rect.zw; // GLSL .ba maps to .zw or .ba in Slang (using .zw is typical) - float2 origin = uniforms.rect.xy; + float2 size = uniforms.size; float thickness = uniforms.params[0]; float corner_radius = uniforms.params[1]; - // Position must be relative to the center of the rectangle of (size) located at (origin) - // frag_coord.xy maps directly to gl_FragCoord.xy - float2 position = frag_coord.xy - size / 2.0 - origin; + // Position in pixels relative to the center of the rectangle. Not + // computed from SV_Position, as its origin differs between backends. + float2 position = uv * size - size / 2.0; // Calculate distance to rounded rectangle float dist = rounded_rectangle_sdf(position, size * 0.5 - corner_radius, corner_radius); diff --git a/kitty/shaders/slang.py b/kitty/shaders/slang.py index 7e804feef..f38945fea 100644 --- a/kitty/shaders/slang.py +++ b/kitty/shaders/slang.py @@ -1293,6 +1293,17 @@ def fixup_opengl_code(glsl_code: str, shader_name: str, existing_metadata: GLSLM return replacements[m.group(1)] ans = re.sub(r'\b(' + '|'.join(re.escape(word) for word in replacements) + r')\b', sub, ans) + if not is_fragment_shader: + # Shaders produce positions for a render target with its origin at + # the top left, so NDC y=-1 is the top. OpenGL window framebuffers + # have their origin at the bottom left, the OpenGL driver sets + # kitty_flip_y to -1 when rendering to them, see Surface in + # gpu/opengl/driver.c + ans, n = re.subn(r'^void main\(\)$', 'void kitty_vertex_main()', ans, flags=re.MULTILINE) + if n != 1: + raise ValueError(f'Could not find the main() function in the vertex shader: {shader_name}') + ans += '\n\nuniform float kitty_flip_y;\n\nvoid main()\n{\n kitty_vertex_main();\n gl_Position.y *= kitty_flip_y;\n}\n' + # Slang emits `{ }` style struct initializers which aren't valid in GLSL 140; # convert them to GLSL constructor call syntax. ans = re.sub( diff --git a/kitty/shaders/trail.slang b/kitty/shaders/trail.slang index 45912f0dc..0d2fd5fc9 100644 --- a/kitty/shaders/trail.slang +++ b/kitty/shaders/trail.slang @@ -40,7 +40,8 @@ fragment_main(float2 frag_pos: TEXCOORD) float opacity = uniforms.trail_opacity; // Evaluate if the fragment falls inside the bounding box of the cursor float in_x = step(uniforms.cursor_edge_x[0], frag_pos.x) * step(frag_pos.x, uniforms.cursor_edge_x[1]); - float in_y = step(uniforms.cursor_edge_y[1], frag_pos.y) * step(frag_pos.y, uniforms.cursor_edge_y[0]); + // NDC y increases downwards, so the top edge, edge 0, is the smaller one + float in_y = step(uniforms.cursor_edge_y[0], frag_pos.y) * step(frag_pos.y, uniforms.cursor_edge_y[1]); // Mask out opacity inside the active cursor area opacity *= 1.0f - (in_x * in_y); diff --git a/kitty/state.c b/kitty/state.c index c549a3580..e41b065e4 100644 --- a/kitty/state.c +++ b/kitty/state.c @@ -778,7 +778,7 @@ pyset_borders_rects(PyObject *self UNUSED, PyObject *args) { r->left = gl_pos_x(r->px.left, osw->viewport_width); r->top = gl_pos_y(r->px.top, osw->viewport_height); r->right = r->left + gl_size(r->px.right - r->px.left, osw->viewport_width); - r->bottom = r->top - gl_size(r->px.bottom - r->px.top, osw->viewport_height); + r->bottom = r->top + gl_size(r->px.bottom - r->px.top, osw->viewport_height); r->color = color; r->border_type = border_type; r->horizontal = horizontal; diff --git a/kitty_tests/graphics.py b/kitty_tests/graphics.py index f3d69b543..e0b469a17 100644 --- a/kitty_tests/graphics.py +++ b/kitty_tests/graphics.py @@ -171,7 +171,7 @@ def put_helpers(self, cw, ch, cols=10, lines=5): cmd = 'a=p,i=%d,%s' % (imgid, put_cmd(**kw)) return imgid, parse_response_with_ids(send_command(screen, cmd)) - def layers(screen, scrolled_by=0, xstart=-1, ystart=1): + def layers(screen, scrolled_by=0, xstart=-1, ystart=-1): return screen.grman.update_layers(scrolled_by, xstart, ystart, dx, dy, screen.columns, screen.lines, cw, ch) def rect_eq(r, left, top, right, bottom): @@ -929,7 +929,7 @@ class TestGraphics(BaseTest): l0 = layers(s) self.ae(len(l0), 1) rect_eq(l0[0]['src_rect'], 0, 0, 1, 1) - rect_eq(l0[0]['dest_rect'], -1, 1, -1 + dx, 1 - dy) + rect_eq(l0[0]['dest_rect'], -1, -1, -1 + dx, -1 + dy) self.ae(l0[0]['group_count'], 1) self.ae(s.cursor.x, 1), self.ae(s.cursor.y, 0) src_width, src_height = 3, 5 @@ -942,9 +942,9 @@ class TestGraphics(BaseTest): self.ae(l2[1], l0[0]) rect_eq(l2[0]['src_rect'], 2 / 10, 1 / 20, (2 + 3) / 10, (1 + 5) / 20) self.ae(l2[0]['group_count'], 2) - left, top = -1 + dx + 3 * dx / cw, 1 - 1 * dy / ch + left, top = -1 + dx + 3 * dx / cw, -1 + 1 * dy / ch right = -1 + (1 + s.columns) * dx - bottom = 1 - dy + bottom = -1 + dy rect_eq(l2[0]['dest_rect'], left, top, right, bottom) self.ae(s.cursor.x, 0), self.ae(s.cursor.y, 1) self.ae(put_image(s, 10, 20, cursor_movement=1)[1], 'OK') @@ -953,7 +953,7 @@ class TestGraphics(BaseTest): self.assertEqual(s.grman.disk_cache.total_size, 0) self.ae(put_image(s, 2 * cw, 2 * ch, num_cols=3)[1], 'OK') self.ae((s.cursor.x, s.cursor.y), (3, 2)) - rect_eq(layers(s)[0]['dest_rect'], -1, 1, -1 + 3 * dx, 1 - 3 * dy) + rect_eq(layers(s)[0]['dest_rect'], -1, -1, -1 + 3 * dx, -1 + 3 * dy) def test_graphics_put_with_pixel_offsets(self): cw, ch = 10, 20 @@ -1044,7 +1044,7 @@ class TestGraphics(BaseTest): return round(((x + 1) / 2) * s.columns) def y(y): - return int(((-y + 1) / 2) * s.lines) + return int(((y + 1) / 2) * s.lines) for i in layers(s): d = i['dest_rect'] @@ -1310,7 +1310,7 @@ class TestGraphics(BaseTest): self.ae(len(refs), 8) for i in range(8): self.ae(refs[i]['src_rect'], {'left': 0.0, 'top': 0.125 * i, 'right': 1.0, 'bottom': 0.125 * (i + 1)}) - self.ae(refs[i]['dest_rect']['top'], 1 - 0.25 * i) + self.ae(refs[i]['dest_rect']['top'], -1 + 0.25 * i) # Now set margins to lines 3 and 6. s.set_margins(3, 6) # 1-based indexing # Scroll two lines down (i.e. move lines 3..6 up). @@ -1324,20 +1324,20 @@ class TestGraphics(BaseTest): self.ae(len(refs), 6) # Lines 1 and 2 are outside of the region, not scrolled. self.ae(refs[0]['src_rect'], {'left': 0.0, 'top': 0.0, 'right': 1.0, 'bottom': 0.125}) - self.ae(refs[0]['dest_rect']['top'], 1.0) + self.ae(refs[0]['dest_rect']['top'], -1.0) self.ae(refs[1]['src_rect'], {'left': 0.0, 'top': 0.125 * 1, 'right': 1.0, 'bottom': 0.125 * 2}) - self.ae(refs[1]['dest_rect']['top'], 1.0 - 0.25 * 1) + self.ae(refs[1]['dest_rect']['top'], -1.0 + 0.25 * 1) # Lines 3 and 4 are erased. # Lines 5 and 6 are now higher. self.ae(refs[2]['src_rect'], {'left': 0.0, 'top': 0.125 * 4, 'right': 1.0, 'bottom': 0.125 * 5}) - self.ae(refs[2]['dest_rect']['top'], 1.0 - 0.25 * 2) + self.ae(refs[2]['dest_rect']['top'], -1.0 + 0.25 * 2) self.ae(refs[3]['src_rect'], {'left': 0.0, 'top': 0.125 * 5, 'right': 1.0, 'bottom': 0.125 * 6}) - self.ae(refs[3]['dest_rect']['top'], 1.0 - 0.25 * 3) + self.ae(refs[3]['dest_rect']['top'], -1.0 + 0.25 * 3) # Lines 7 and 8 are outside of the region. self.ae(refs[4]['src_rect'], {'left': 0.0, 'top': 0.125 * 6, 'right': 1.0, 'bottom': 0.125 * 7}) - self.ae(refs[4]['dest_rect']['top'], 1.0 - 0.25 * 6) + self.ae(refs[4]['dest_rect']['top'], -1.0 + 0.25 * 6) self.ae(refs[5]['src_rect'], {'left': 0.0, 'top': 0.125 * 7, 'right': 1.0, 'bottom': 0.125 * 8}) - self.ae(refs[5]['dest_rect']['top'], 1.0 - 0.25 * 7) + self.ae(refs[5]['dest_rect']['top'], -1.0 + 0.25 * 7) # Now scroll three lines up (i.e. move lines 5..6 down). # Line 6 will be erased. s.cursor_position(3, 0) @@ -1350,18 +1350,18 @@ class TestGraphics(BaseTest): self.ae(len(refs), 5) # Lines 1 and 2 are outside of the region, not scrolled. self.ae(refs[0]['src_rect'], {'left': 0.0, 'top': 0.0, 'right': 1.0, 'bottom': 0.125}) - self.ae(refs[0]['dest_rect']['top'], 1.0) + self.ae(refs[0]['dest_rect']['top'], -1.0) self.ae(refs[1]['src_rect'], {'left': 0.0, 'top': 0.125 * 1, 'right': 1.0, 'bottom': 0.125 * 2}) - self.ae(refs[1]['dest_rect']['top'], 1.0 - 0.25 * 1) + self.ae(refs[1]['dest_rect']['top'], -1.0 + 0.25 * 1) # Lines 3, 4 and 6 are erased. # Line 5 is now lower. self.ae(refs[2]['src_rect'], {'left': 0.0, 'top': 0.125 * 4, 'right': 1.0, 'bottom': 0.125 * 5}) - self.ae(refs[2]['dest_rect']['top'], 1.0 - 0.25 * 5) + self.ae(refs[2]['dest_rect']['top'], -1.0 + 0.25 * 5) # Lines 7 and 8 are outside of the region. self.ae(refs[3]['src_rect'], {'left': 0.0, 'top': 0.125 * 6, 'right': 1.0, 'bottom': 0.125 * 7}) - self.ae(refs[3]['dest_rect']['top'], 1.0 - 0.25 * 6) + self.ae(refs[3]['dest_rect']['top'], -1.0 + 0.25 * 6) self.ae(refs[4]['src_rect'], {'left': 0.0, 'top': 0.125 * 7, 'right': 1.0, 'bottom': 0.125 * 8}) - self.ae(refs[4]['dest_rect']['top'], 1.0 - 0.25 * 7) + self.ae(refs[4]['dest_rect']['top'], -1.0 + 0.25 * 7) def test_unicode_placeholders_reverse_scroll(self): # A cell image pushed off the bottom of the screen by a reverse scroll @@ -1445,7 +1445,7 @@ class TestGraphics(BaseTest): index_lines(s.lines, 5) def ref_rows(refs): - return sorted(round((1 - r['dest_rect']['top']) / dy) - s.scrolled_by for r in refs) + return sorted(round((r['dest_rect']['top'] + 1) / dy) - s.scrolled_by for r in refs) before = ref_rows(scroll_view(6, True)) self.ae(before, [-3, -2]) @@ -1479,11 +1479,11 @@ class TestGraphics(BaseTest): def live_layers(s): offset = s.pixel_scroll_offset_y / ch if s.pixel_scroll_offset_y else 0 - return s.grman.update_layers(s.scrolled_by, -1, 1, 2 / s.columns, dy(s), s.columns, s.lines, cw, ch, offset) + return s.grman.update_layers(s.scrolled_by, -1, -1, 2 / s.columns, dy(s), s.columns, s.lines, cw, ch, offset) def image_rows(s, layers): offset = s.rendered_scroll_state()[1] / ch - return [round((1 - r['dest_rect']['top']) / dy(s) - offset) for r in layers] + return [round((r['dest_rect']['top'] + 1) / dy(s) - offset) for r in layers] def text_row(s): for y in range(s.lines): @@ -1612,7 +1612,7 @@ class TestGraphics(BaseTest): def ref_rows(scrolled_by=0): s.update_only_line_graphics_data() - return sorted(round((1 - r['dest_rect']['top']) / dy) - scrolled_by for r in layers(s, scrolled_by)) + return sorted(round((r['dest_rect']['top'] + 1) / dy) - scrolled_by for r in layers(s, scrolled_by)) def rows_in_history(): # Render the history lines as when the view is scrolled back @@ -1728,14 +1728,14 @@ class TestGraphics(BaseTest): put_image(s, cw, 4 * ch, num_cols=1, num_lines=2, no_id=True) # 10x80 px image scaled into 1x2 cells at (0, 0) self.ae(s.grman.image_count, 1) self.ae(layers(s)[0]['src_rect'], {'left': 0.0, 'top': 0.0, 'right': 1.0, 'bottom': 1.0}) - rect_eq(layers(s)[0]['dest_rect'], -1, 1, -1 + dx, 1 - 2 * dy) + rect_eq(layers(s)[0]['dest_rect'], -1, -1, -1 + dx, -1 + 2 * dy) while s.cursor.y != 2: s.index() s.index() # scroll up, the top row of the image is clipped l0 = layers(s) self.ae(len(l0), 1) self.ae(l0[0]['src_rect'], {'left': 0.0, 'top': 0.5, 'right': 1.0, 'bottom': 1.0}) - rect_eq(l0[0]['dest_rect'], -1, 1, -1 + dx, 1 - dy) + rect_eq(l0[0]['dest_rect'], -1, -1, -1 + dx, -1 + dy) s.index() self.ae(s.grman.image_count, 0) # Now check clipping of a scaled image at the bottom margin @@ -1749,20 +1749,20 @@ class TestGraphics(BaseTest): l0 = layers(s) self.ae(len(l0), 1) self.ae(l0[0]['src_rect'], {'left': 0.0, 'top': 0.0, 'right': 1.0, 'bottom': 0.5}) - rect_eq(l0[0]['dest_rect'], -1, 1 - 2 * dy, -1 + dx, 1 - 3 * dy) + rect_eq(l0[0]['dest_rect'], -1, -1 + 2 * dy, -1 + dx, -1 + 3 * dy) s.reverse_index() self.ae(s.grman.image_count, 0) # Scaling specified via c= only, with the height derived from the aspect ratio s.reset() s.set_margins(1, 3) put_image(s, 2 * cw, 4 * ch, num_cols=1, no_id=True) # 20x80 px image scaled into 1 col => 10x40 px => 1x2 cells - rect_eq(layers(s)[0]['dest_rect'], -1, 1, -1 + dx, 1 - 2 * dy) + rect_eq(layers(s)[0]['dest_rect'], -1, -1, -1 + dx, -1 + 2 * dy) while s.cursor.y != 2: s.index() s.index() # scroll up, the top row of the image is clipped l0 = layers(s) self.ae(l0[0]['src_rect'], {'left': 0.0, 'top': 0.5, 'right': 1.0, 'bottom': 1.0}) - rect_eq(l0[0]['dest_rect'], -1, 1, -1 + dx, 1 - dy) + rect_eq(l0[0]['dest_rect'], -1, -1, -1 + dx, -1 + dy) s.index() self.ae(s.grman.image_count, 0) s.reset() diff --git a/kitty_tests/slang.py b/kitty_tests/slang.py index 88af1b7a4..26f3a4488 100644 --- a/kitty_tests/slang.py +++ b/kitty_tests/slang.py @@ -75,6 +75,15 @@ class TestSlang(BaseTest): self.assertLessEqual(b['size'], PUSH_CONSTANTS_MAX_SIZE, name) for b in m['param_blocks']: self.assertNotIn('stage', b, name) + if target.family == 'glsl': + # OpenGL window framebuffers have their origin at the bottom left, + # vertex shaders flip y when kitty_flip_y is -1, see fixup_opengl_code() + for name in os.listdir(tdir): + if name.endswith('.vert.glsl'): + with open(os.path.join(tdir, name)) as f: + src = f.read() + self.assertIn('uniform float kitty_flip_y;', src, name) + self.assertIn('gl_Position.y *= kitty_flip_y;', src, name) if 'trail.json' in names: with open(os.path.join(tdir, 'trail.json')) as f: m = json.load(f)