diff --git a/gpu/api.h b/gpu/api.h index c525df4cb..87308803b 100644 --- a/gpu/api.h +++ b/gpu/api.h @@ -49,7 +49,7 @@ #include #include -#define KITTY_GPU_API_VERSION 3u +#define KITTY_GPU_API_VERSION 4u #define KITTY_GPU_DRIVER_ENTRY_POINT "kitty_gpu_driver_load" #define GPU_NULL_HANDLE ((uint64_t)0) @@ -252,8 +252,9 @@ typedef struct GPUBinding { } GPUBinding; // Parameter blocks hold the small, frequently changing, parameters of a -// pipeline: the uniform parameters of each entry point, and uniform blocks -// whose contents are constant for the lifetime of the pipeline. Their layout +// pipeline: the push constant block, holding the uniform parameters shared +// by all stages of the pipeline, and uniform blocks whose contents are +// constant for the lifetime of the pipeline. Their layout // comes from the reflection data. kitty writes their contents into memory it // owns, laid out as described here, and passes it to set_params() before // drawing. Values persist with the pipeline until set again. Drivers are free @@ -276,13 +277,12 @@ typedef struct GPUParamField { } GPUParamField; typedef struct GPUParamBlock { - // For the uniform parameters of an entry point name is NULL and stage is - // the stage of the entry point. For uniform blocks name is the name of the - // type of the block in the Slang source, stage is zero and slot is the - // binding slot of the block, which drivers that implement it as a - // uniform buffer must use. + // For the push constant block name is NULL and slot is -1. Its contents + // are used by every stage of the pipeline and are at most 128 bytes. For + // uniform blocks name is the name of the type of the block in the Slang + // source and slot is the binding slot of the block, which drivers that + // implement it as a uniform buffer must use. const char *name; - GPUShaderStage stage; int32_t slot; uint32_t size; // size in bytes of the block const GPUParamField *fields; diff --git a/kitty/gpu.c b/kitty/gpu.c index c27d3ffcc..8264e01bc 100644 --- a/kitty/gpu.c +++ b/kitty/gpu.c @@ -254,8 +254,7 @@ typedef struct ParamField { } ParamField; typedef struct ParamBlock { - char *name; // NULL for the uniform parameters of an entry point - GPUShaderStage stage; + char *name; // NULL for the push constant block int32_t slot; uint32_t size; uint8_t *data; // the contents, laid out as described by the fields @@ -264,12 +263,9 @@ typedef struct ParamBlock { size_t num_fields; } ParamBlock; -// The fields with a given name, at most one per stage +// The field with a given name typedef struct ParamRef { - uint8_t num; - struct { - uint16_t block, field; - } items[2]; + uint16_t block, field; } ParamRef; typedef struct ProgramParams { @@ -413,18 +409,6 @@ metadata_str(PyObject *d, const char *key) { return v ? PyUnicode_AsUTF8(v) : NULL; } -static bool -parse_stage(const char *s, GPUShaderStage *ans) { - if (strcmp(s, "vertex") == 0) *ans = GPU_SHADER_VERTEX; - else if (strcmp(s, "fragment") == 0) *ans = GPU_SHADER_FRAGMENT; - else if (!s[0]) *ans = 0; - else { - PyErr_Format(PyExc_ValueError, "Unknown shader stage: %s", s); - return false; - } - return true; -} - static bool parse_scalar(const char *s, GPUParamScalar *ans) { if (strcmp(s, "float") == 0) *ans = GPU_PARAM_FLOAT; @@ -449,8 +433,8 @@ parse_param_blocks(PyObject *metadata, ProgramParams *pp) { for (size_t b = 0; b < num_blocks; b++) { PyObject *src = PyList_GET_ITEM(blocks, b); ParamBlock *pb = pp->blocks + b; - const char *name = metadata_str(src, "name"), *stage = metadata_str(src, "stage"); - if (!name || !stage || !parse_stage(stage, &pb->stage)) return false; + const char *name = metadata_str(src, "name"); + if (!name) return false; if (name[0] && !(pb->name = strdup(name))) goto oom; if (!metadata_int(src, "slot", &pb->slot) || !metadata_uint(src, "size", &pb->size)) return false; if (!(pb->data = calloc(1, MAX(1u, pb->size)))) goto oom; @@ -498,20 +482,12 @@ index_params(int program, ProgramParams *pp) { for (size_t i = 0; i < pp->blocks[b].num_fields; i++) { const char *name = pp->blocks[b].fields[i].name; ProgramMetadataEntry *e; - ParamRef *ref; - if (find_program_metadata(program, name, PROGRAM_PARAM, &e)) ref = pp->refs + e->location; - else { - ref = pp->refs + pp->num_refs; - insert_program_metadata(program, name, (ProgramMetadataEntry){.kind = PROGRAM_PARAM, .location = (int32_t)pp->num_refs}); - pp->num_refs++; - } - if (ref->num >= arraysz(ref->items)) { - PyErr_Format(PyExc_ValueError, "The shader parameter %s is used in too many parameter blocks", name); + if (find_program_metadata(program, name, PROGRAM_PARAM, &e)) { + PyErr_Format(PyExc_ValueError, "The shader parameter %s is present in more than one parameter block", name); return false; } - ref->items[ref->num].block = (uint16_t)b; - ref->items[ref->num].field = (uint16_t)i; - ref->num++; + insert_program_metadata(program, name, (ProgramMetadataEntry){.kind = PROGRAM_PARAM, .location = (int32_t)pp->num_refs}); + pp->refs[pp->num_refs++] = (ParamRef){.block = (uint16_t)b, .field = (uint16_t)i}; } } return true; @@ -657,7 +633,7 @@ compile_gpu_program(int program, const char *vertex, size_t vertex_size, const c } for (size_t b = 0, fi = 0; b < pp.num_blocks; b++) { const ParamBlock *pb = pp.blocks + b; - gpb[b] = (GPUParamBlock){.name = pb->name, .stage = pb->stage, .slot = pb->slot, .size = pb->size, .fields = gpf + fi, .num_fields = pb->num_fields}; + gpb[b] = (GPUParamBlock){.name = pb->name, .slot = pb->slot, .size = pb->size, .fields = gpf + fi, .num_fields = pb->num_fields}; for (size_t i = 0; i < pb->num_fields; i++, fi++) { const ParamField *f = pb->fields + i; gpf[fi] = @@ -705,20 +681,18 @@ write_param(int32_t handle, GPUParamScalar scalar, uint32_t components, uint32_t if (r >= pp->num_refs) return; const ParamRef *ref = pp->refs + r; const size_t elem = 4u * components; - for (uint8_t i = 0; i < ref->num; i++) { - ParamBlock *pb = pp->blocks + ref->items[i].block; - ParamField *f = pb->fields + ref->items[i].field; - const bool scalar_ok = f->scalar == scalar || (f->scalar == GPU_PARAM_BOOL && scalar == GPU_PARAM_INT); - if (!scalar_ok || f->components != components || count > f->count) { - if (!f->type_error_logged) { - f->type_error_logged = true; - log_error("Setting the shader parameter: %s in GPU program: %d with a value of the wrong type", f->name, program); - } - continue; + ParamBlock *pb = pp->blocks + ref->block; + ParamField *f = pb->fields + ref->field; + const bool scalar_ok = f->scalar == scalar || (f->scalar == GPU_PARAM_BOOL && scalar == GPU_PARAM_INT); + if (!scalar_ok || f->components != components || count > f->count) { + if (!f->type_error_logged) { + f->type_error_logged = true; + log_error("Setting the shader parameter: %s in GPU program: %d with a value of the wrong type", f->name, program); } - for (uint32_t e = 0; e < count; e++) memcpy(pb->data + f->offset + (size_t)e * f->stride, (const uint8_t *)values + e * elem, elem); - pb->dirty = true; + return; } + for (uint32_t e = 0; e < count; e++) memcpy(pb->data + f->offset + (size_t)e * f->stride, (const uint8_t *)values + e * elem, elem); + pb->dirty = true; } void diff --git a/kitty/gpu.h b/kitty/gpu.h index ef9333b22..8427cd136 100644 --- a/kitty/gpu.h +++ b/kitty/gpu.h @@ -369,8 +369,8 @@ void free_program(int program); bool compile_gpu_program(int program, const char *vertex, size_t vertex_size, const char *fragment, size_t fragment_size, PyObject *metadata); int32_t attrib_location(int program, const char *name); void free_program_layouts(void); -// Parameters, the uniform parameters of the entry points and the pipeline -// constant blocks of a program. Values are written into memory owned by +// Parameters, the push constant block holding the uniform parameters and the +// pipeline constant blocks of a program. Values are written into memory owned by // kitty and passed to the driver before the next draw call using the // program. A handle identifies a parameter of a program, negative handles // are ignored by the setters. diff --git a/kitty/shaders/bgimage.slang b/kitty/shaders/bgimage.slang index 8c6373287..06cefdcb6 100644 --- a/kitty/shaders/bgimage.slang +++ b/kitty/shaders/bgimage.slang @@ -20,6 +20,17 @@ import alpha_blend; static const float2 tex_map[4] = { float2(tex_left, tex_top), float2(tex_left, tex_bottom), float2(tex_right, tex_bottom), float2(tex_right, tex_top) }; +// 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 { + float tiled; + float4 sizes; + float4 positions; + float4 background; +}; +[[vk::push_constant]] +ConstantBuffer uniforms; + struct VertexOutput { float2 texcoord : TEXCOORD; float4 position : SV_Position; @@ -41,19 +52,20 @@ tiling_factor(int i, float4 sizes, float tiled) { // Main Vertex Shader Entry Point [shader("vertex")] VertexOutput -vertex_main(uint vertex_id: SV_VertexID, uniform float tiled, uniform float4 sizes, uniform float4 positions, ) { +vertex_main(uint vertex_id: SV_VertexID) { const float2 pos_map[4] = { - float2(positions[left], positions[top]), - float2(positions[left], positions[bottom]), - float2(positions[right], positions[bottom]), - float2(positions[right], positions[top]) + float2(uniforms.positions[left], uniforms.positions[top]), + float2(uniforms.positions[left], uniforms.positions[bottom]), + float2(uniforms.positions[right], uniforms.positions[bottom]), + float2(uniforms.positions[right], uniforms.positions[top]) }; VertexOutput output; // Calculate outputs float2 tex_coords = tex_map[vertex_id]; - output.texcoord = float2(tex_coords[x_axis] * tiling_factor(x_axis, sizes, tiled), tex_coords[y_axis] * tiling_factor(y_axis, sizes, tiled)); + output.texcoord = float2( + tex_coords[x_axis] * tiling_factor(x_axis, uniforms.sizes, uniforms.tiled), tex_coords[y_axis] * tiling_factor(y_axis, uniforms.sizes, uniforms.tiled)); output.position = float4(pos_map[vertex_id], 0.0, 1.0); return output; } @@ -65,11 +77,11 @@ uniform Sampler2D image; // binding slots: see SHADER_BINDING_SLOTS in slang.py // Main Fragment Shader Entry Point [shader("fragment")] float4 -fragment_main(float2 texcoord: TEXCOORD, uniform float4 background) +fragment_main(float2 texcoord: TEXCOORD) : SV_Target { // Sample the texture using Slang's intrinsic texture object syntax float4 color = image.Sample(texcoord); // Compute final color with alpha blending - float4 premult_color = alpha_blend(color, background); + float4 premult_color = alpha_blend(color, uniforms.background); return premult_color; } diff --git a/kitty/shaders/blit.slang b/kitty/shaders/blit.slang index bfd9061d9..9112b9519 100644 --- a/kitty/shaders/blit.slang +++ b/kitty/shaders/blit.slang @@ -7,6 +7,15 @@ import alpha_blend; import utils; import linear2srgb; +// 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 src_rect; + float4 dest_rect; +}; +[[vk::push_constant]] +ConstantBuffer uniforms; + struct VSOutput { float2 texcoord : TEXCOORD; float4 position : SV_Position; @@ -15,8 +24,8 @@ struct VSOutput { [shader("vertex")] VSOutput -vertex_main(uint vertex_id: SV_VertexID, uniform float4 src_rect, uniform float4 dest_rect, ) { - BlitOutput ans = get_coords_for_blit(vertex_id, src_rect, dest_rect); +vertex_main(uint vertex_id: SV_VertexID) { + BlitOutput ans = get_coords_for_blit(vertex_id, uniforms.src_rect, uniforms.dest_rect); return { ans.texcoord, float4(ans.position[0], ans.position[1], 0.0, 1.0) }; } diff --git a/kitty/shaders/border.slang b/kitty/shaders/border.slang index db368574c..6b8614fa5 100644 --- a/kitty/shaders/border.slang +++ b/kitty/shaders/border.slang @@ -31,6 +31,14 @@ struct Colors { ConstantBuffer clrs; #define colors clrs.colors +// 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 { + float background_opacity; +}; +[[vk::push_constant]] +ConstantBuffer uniforms; + // Vertex attributes matching GLSL input locations struct VertexInput { float4 rect; // left, top, right, bottom @@ -69,7 +77,7 @@ as_color_vector(uint c, int shift) { [shader("vertex")] VertexOutput -vertex_main(float4 rect, uint rect_color, uniform float background_opacity, uint vertex_id: SV_VertexID) { +vertex_main(float4 rect, uint rect_color, uint vertex_id: SV_VertexID) { VertexOutput output; uint2 pos = pos_map[vertex_id]; @@ -88,7 +96,7 @@ vertex_main(float4 rect, uint rect_color, uniform float background_opacity, uint abs((float(rc) - ACTIVE_BORDER_COLOR) * (float(rc) - INACTIVE_BORDER_COLOR) * (float(rc) - BELL_BORDER_COLOR) * (float(rc) - TAB_BAR_EDGE_LEFT_COLOR) * (float(rc) - TAB_BAR_EDGE_RIGHT_COLOR))); - float final_opacity = if_one_then(is_not_a_border, background_opacity, 1.); + float final_opacity = if_one_then(is_not_a_border, uniforms.background_opacity, 1.); output.color_premul = vec4_premul(color3, final_opacity); return output; diff --git a/kitty/shaders/cell.slang b/kitty/shaders/cell.slang index 1f8cea6ae..bcc7d5b2a 100644 --- a/kitty/shaders/cell.slang +++ b/kitty/shaders/cell.slang @@ -34,6 +34,16 @@ static const uint SPRITE_COLORED_SHIFT = 31u; // background. Packed into an existing flat varying to not use another slot. static const uint SKIP_TEXT_FLAG = 0x80000000u; +// 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 { + uint draw_bg_bitfield; + float text_contrast; + float text_gamma_adjustment; +}; +[[vk::push_constant]] +ConstantBuffer uniforms; + struct VertexOutput { float4 position : SV_Position; @@ -148,8 +158,7 @@ vertex_main( [[vk::location(1)]] uint2 sprite_idx, [[vk::location(2)]] uint is_selected, uint vertex_id: SV_VertexID, - uint instance_id: SV_InstanceID, - uniform uint draw_bg_bitfield, ) { + uint instance_id: SV_InstanceID) { VertexOutput vo; BackgroundOutput bo = compute_background(colors, sprite_idx, is_selected, instance_id, vertex_id); @@ -208,7 +217,7 @@ vertex_main( // draw_bg_bitfield has bit 0 set to draw default bg cells and bit 1 set to draw non-default bg cells float cell_has_non_default_bg = 1.f - bo.cell_has_default_bg; uint draw_bg_mask = uint(2.f * cell_has_non_default_bg + bo.cell_has_default_bg); // 1 if has default bg else 2 - float draw_bg = step(0.5, float(draw_bg_bitfield & draw_bg_mask)); + float draw_bg = step(0.5, float(uniforms.draw_bg_bitfield & draw_bg_mask)); bgpremul *= draw_bg; vo.effective_background_premul = bgpremul; } @@ -308,7 +317,7 @@ adjust_foreground_contrast_with_background(float4 text_fg, float3 bg, float text [shader("fragment")] float4 -fragment_main(VertexOutput vo, uniform float text_contrast, uniform float text_gamma_adjustment, ) +fragment_main(VertexOutput vo) : SV_Target { float4 ans_premul = 0; if (!ONLY_FOREGROUND) ans_premul = vo.effective_background_premul; @@ -319,7 +328,7 @@ fragment_main(VertexOutput vo, uniform float text_contrast, uniform float text_g if (!ONLY_BACKGROUND && (vo.underline_exclusion_pos & SKIP_TEXT_FLAG) == 0u) { // blend in the foreground color float4 text_fg = load_text_foreground_color(vo.sprite_pos, vo.colored_sprite, vo.cell_foreground); - text_fg = adjust_foreground_contrast_with_background(text_fg, vo.background, text_contrast, text_gamma_adjustment); + text_fg = adjust_foreground_contrast_with_background(text_fg, vo.background, uniforms.text_contrast, uniforms.text_gamma_adjustment); float4 text_fg_premul = calculate_premul_foreground_from_sprites( vo.sprite_pos, vo.underline_pos, diff --git a/kitty/shaders/graphics.slang b/kitty/shaders/graphics.slang index b2ca7c2aa..f9a903cac 100644 --- a/kitty/shaders/graphics.slang +++ b/kitty/shaders/graphics.slang @@ -10,6 +10,18 @@ extern static const bool is_alpha_mask = false; extern static const bool texture_is_not_premultiplied = true; +// 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 src_rect; + float4 dest_rect; + float3 amask_fg; + float4 amask_bg_premult; + float extra_alpha; +}; +[[vk::push_constant]] +ConstantBuffer uniforms; + struct VSOutput { float2 texcoord : TEXCOORD; float4 position : SV_Position; @@ -18,8 +30,8 @@ struct VSOutput { [shader("vertex")] VSOutput -vertex_main(uint vertex_id: SV_VertexID, uniform float4 src_rect, uniform float4 dest_rect, ) { - BlitOutput ans = get_coords_for_blit(vertex_id, src_rect, dest_rect); +vertex_main(uint vertex_id: SV_VertexID) { + BlitOutput ans = get_coords_for_blit(vertex_id, uniforms.src_rect, uniforms.dest_rect); return { ans.texcoord, float4(ans.position[0], ans.position[1], 0.0, 1.0) }; } @@ -28,14 +40,14 @@ uniform Sampler2D image; // binding slots: see SHADER_BINDING_SLOTS in slang.py [shader("fragment")] float4 -fragment_main(float2 texcoord: TEXCOORD, uniform float3 amask_fg, uniform float4 amask_bg_premult, uniform float extra_alpha) +fragment_main(float2 texcoord: TEXCOORD) : SV_Target { float4 color = image.Sample(texcoord); if (is_alpha_mask) { - color = float4(amask_fg, color.r); + color = float4(uniforms.amask_fg, color.r); color = vec4_premul(color); - color = alpha_blend_premul(color, amask_bg_premult); - } else color.a *= extra_alpha; + color = alpha_blend_premul(color, uniforms.amask_bg_premult); + } else color.a *= uniforms.extra_alpha; if (texture_is_not_premultiplied) color = vec4_premul(color); diff --git a/kitty/shaders/indexed_graphics.slang b/kitty/shaders/indexed_graphics.slang index 5794806f8..a73afa208 100644 --- a/kitty/shaders/indexed_graphics.slang +++ b/kitty/shaders/indexed_graphics.slang @@ -14,6 +14,17 @@ import background; // which needs only a single pixel read per fragment. extern static const bool is_scaled = true; +// 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 src_rect; + float4 dest_rect; + uint has_alpha; + float extra_alpha; +}; +[[vk::push_constant]] +ConstantBuffer uniforms; + struct VSOutput { float2 texcoord : TEXCOORD; float4 position : SV_Position; @@ -21,8 +32,8 @@ struct VSOutput { [shader("vertex")] VSOutput -vertex_main(uint vertex_id: SV_VertexID, uniform float4 src_rect, uniform float4 dest_rect, ) { - BlitOutput ans = get_coords_for_blit(vertex_id, src_rect, dest_rect); +vertex_main(uint vertex_id: SV_VertexID) { + BlitOutput ans = get_coords_for_blit(vertex_id, uniforms.src_rect, uniforms.dest_rect); return { ans.texcoord, float4(ans.position[0], ans.position[1], 0.0, 1.0) }; } @@ -40,7 +51,7 @@ premult_color_at(int2 pos, uint has_alpha) { [shader("fragment")] float4 -fragment_main(float2 texcoord: TEXCOORD, uniform uint has_alpha, uniform float extra_alpha) +fragment_main(float2 texcoord: TEXCOORD) : SV_Target { // Integer textures cannot be filtered and anyway the palette lookup must // happen before interpolation, so do bilinear filtering here. @@ -50,13 +61,13 @@ fragment_main(float2 texcoord: TEXCOORD, uniform uint has_alpha, uniform float e // When the image is drawn at its natural size every fragment is at the // center of a pixel, so just read that pixel. is_scaled is a compile time // constant so this is not a branch in the shader. - if (!is_scaled) return premult_color_at(clamp(int2(texcoord * float2(width, height)), int2(0, 0), limit), has_alpha) * extra_alpha; + if (!is_scaled) return premult_color_at(clamp(int2(texcoord * float2(width, height)), int2(0, 0), limit), uniforms.has_alpha) * uniforms.extra_alpha; const float2 pos = texcoord * float2(width, height) - 0.5; const float2 base = floor(pos); const float2 frac = pos - base; const int2 p0 = clamp(int2(base), int2(0, 0), limit); const int2 p1 = clamp(int2(base) + int2(1, 1), int2(0, 0), limit); - const float4 top = lerp(premult_color_at(p0, has_alpha), premult_color_at(int2(p1.x, p0.y), has_alpha), frac.x); - const float4 bottom = lerp(premult_color_at(int2(p0.x, p1.y), has_alpha), premult_color_at(p1, has_alpha), frac.x); - return lerp(top, bottom, frac.y) * extra_alpha; + const float4 top = lerp(premult_color_at(p0, uniforms.has_alpha), premult_color_at(int2(p1.x, p0.y), uniforms.has_alpha), frac.x); + const float4 bottom = lerp(premult_color_at(int2(p0.x, p1.y), uniforms.has_alpha), premult_color_at(p1, uniforms.has_alpha), frac.x); + return lerp(top, bottom, frac.y) * uniforms.extra_alpha; } diff --git a/kitty/shaders/padding.slang b/kitty/shaders/padding.slang index e273c6409..4c9bca58f 100644 --- a/kitty/shaders/padding.slang +++ b/kitty/shaders/padding.slang @@ -29,6 +29,35 @@ static const uint2 pad_pos_map[4] = { uint2(0u, 0u) // left, top }; +// 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 { + // The true cell index (into the cell grid) for strip 0's first instance. + uint base_instance; + uint instance_step; + // 1 for the top/bottom strips (the strip runs along x), 0 for left/right. + uint is_horizontal; + // Number of cells per strip (== instance count for a single-strip draw; + // total instances == along_count * num_strips). + uint along_count; + // 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). + float along_start; + float along_step; + // NDC bounds used to extend the first/last cell so the strip fills the + // corners (shared by both strips of a combined draw). + float2 along_clamp; + // Strip-1 parameters. Equal to strip-0 values for single-strip draws so + // the lerp below is always correct regardless of strip count. + uint base_instance2; + float2 across2; +}; +[[vk::push_constant]] +ConstantBuffer uniforms; + struct VertexOutput { float4 color_premul : COLOR_PREMUL; float4 position : SV_Position; @@ -41,61 +70,39 @@ vertex_main( [[vk::location(1)]] uint2 sprite_idx, [[vk::location(2)]] uint is_selected, uint vertex_id: SV_VertexID, - uint instance_id: SV_InstanceID, - // The true cell index (into the cell grid) for strip 0's first instance. - uniform uint base_instance, - uniform uint instance_step, - // 1 for the top/bottom strips (the strip runs along x), 0 for left/right. - uniform uint is_horizontal, - // Number of cells per strip (== instance count for a single-strip draw; - // total instances == along_count * num_strips). - uniform uint along_count, - // The two NDC values of the thin (across) dimension for strip 0. - uniform 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). - uniform float along_start, - uniform float along_step, - // NDC bounds used to extend the first/last cell so the strip fills the - // corners (shared by both strips of a combined draw). - uniform float2 along_clamp, - // Strip-1 parameters. Equal to strip-0 values for single-strip draws so - // the lerp below is always correct regardless of strip count. - uniform uint base_instance2, - uniform float2 across2, ) { + uint instance_id: SV_InstanceID) { VertexOutput vo; // Branchless strip selector: 0.0 for strip 0, 1.0 for strip 1. - float strip_f = float(instance_id / along_count); - uint strip_i = instance_id % along_count; + float strip_f = float(instance_id / uniforms.along_count); + uint strip_i = instance_id % uniforms.along_count; // Select the base cell and across extents for whichever strip this // instance belongs to, using lerp so no divergent branch is emitted. - float fbase = lerp(float(base_instance), float(base_instance2), strip_f); - uint real_id = uint(fbase) + strip_i * instance_step; - float2 chosen_across = lerp(across, across2, strip_f); + float fbase = lerp(float(uniforms.base_instance), float(uniforms.base_instance2), strip_f); + uint real_id = uint(fbase) + strip_i * uniforms.instance_step; + float2 chosen_across = lerp(uniforms.across, uniforms.across2, strip_f); vo.color_premul = padding_background_premul(colors, sprite_idx, is_selected, real_id); uint2 p = pad_pos_map[vertex_id]; - float along_lo = along_start + float(strip_i) * along_step; - float along_hi = along_lo + along_step; + float along_lo = uniforms.along_start + float(strip_i) * uniforms.along_step; + float along_hi = along_lo + uniforms.along_step; // Branch-free selection via lerp(). h selects the strip orientation, s is the // corner component along the strip axis and a the component across it. - float h = float(is_horizontal); + float h = float(uniforms.is_horizontal); float s = lerp(float(p.y), float(p.x), h); float a = lerp(float(p.x), float(p.y), h); // 1 when this is the first/last instance within its strip, else 0. float is_first = 1.0 - min(float(strip_i), 1.0); - float is_last = 1.0 - min(float(along_count - 1u - strip_i), 1.0); + float is_last = 1.0 - min(float(uniforms.along_count - 1u - strip_i), 1.0); float along = lerp(along_lo, along_hi, s); // Extend the first cell's near corner and the last cell's far corner out to // along_clamp so the strip fills the corners. - along = lerp(along, along_clamp.x, is_first * (1.0 - s)); - along = lerp(along, along_clamp.y, is_last * s); + along = lerp(along, uniforms.along_clamp.x, is_first * (1.0 - s)); + along = lerp(along, uniforms.along_clamp.y, is_last * s); float across_v = lerp(chosen_across.x, chosen_across.y, a); // Horizontal strip -> position is (along, across); vertical -> (across, along). diff --git a/kitty/shaders/rounded_rect.slang b/kitty/shaders/rounded_rect.slang index f42e83877..b262521c2 100644 --- a/kitty/shaders/rounded_rect.slang +++ b/kitty/shaders/rounded_rect.slang @@ -16,6 +16,18 @@ import alpha_blend; // See https://github.com/kovidgoyal/kitty/issues/10549 static const float2 vertex_pos_map[4] = { float2(1, 1), float2(1, -1), float2(-1, -1), float2(-1, 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 params; + float4 color; + float4 background_color; + float4 outer_color; +}; +[[vk::push_constant]] +ConstantBuffer uniforms; + [shader("vertex")] float4 vertex_main(uint vertex_id: SV_VertexID) @@ -35,18 +47,13 @@ rounded_rectangle_sdf(float2 p, float2 b, float r) { [shader("fragment")] float4 fragment_main( - uniform float4 rect, - uniform float2 params, - uniform float4 color, - uniform float4 background_color, - uniform float4 outer_color, float4 frag_coord: SV_Position // SV_Position provides gl_FragCoord equivalent in Slang ) : SV_Target { - float2 size = rect.zw; // GLSL .ba maps to .zw or .ba in Slang (using .zw is typical) - float2 origin = rect.xy; - float thickness = params[0]; - float corner_radius = params[1]; + float2 size = uniforms.rect.zw; // GLSL .ba maps to .zw or .ba in Slang (using .zw is typical) + float2 origin = uniforms.rect.xy; + 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 @@ -64,12 +71,12 @@ fragment_main( float outer_coverage = smoothstep(-step_size, step_size, outer_edge); float alpha = outer_coverage - smoothstep(-step_size, step_size, inner_edge); - float4 ans = color; + float4 ans = uniforms.color; ans.a *= alpha; // background_color shows under and inside the border, outer_color fills // the corner regions between the rounded outline and the bounding rect - float4 under = lerp(outer_color, background_color, outer_coverage); + float4 under = lerp(uniforms.outer_color, uniforms.background_color, outer_coverage); // pre-multiplied output return alpha_blend(ans, under); } diff --git a/kitty/shaders/screenshot.slang b/kitty/shaders/screenshot.slang index 61c0462f0..604a60d69 100644 --- a/kitty/shaders/screenshot.slang +++ b/kitty/shaders/screenshot.slang @@ -5,6 +5,16 @@ import blit_common; import linear2srgb; +// 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 src_rect; + float4 dest_rect; + float2 src_size; +}; +[[vk::push_constant]] +ConstantBuffer uniforms; + struct VSOutput { float2 texcoord : TEXCOORD; float4 position : SV_Position; @@ -13,8 +23,8 @@ struct VSOutput { [shader("vertex")] VSOutput -vertex_main(uint vertex_id: SV_VertexID, uniform float4 src_rect, uniform float4 dest_rect, ) { - BlitOutput ans = get_coords_for_blit(vertex_id, src_rect, dest_rect); +vertex_main(uint vertex_id: SV_VertexID) { + BlitOutput ans = get_coords_for_blit(vertex_id, uniforms.src_rect, uniforms.dest_rect); return { ans.texcoord, float4(ans.position[0], ans.position[1], 0.0, 1.0) }; } @@ -33,10 +43,10 @@ safe_unpremult_to_linear(float4 s) { [shader("fragment")] float4 -fragment_main(float2 texcoord: TEXCOORD, uniform float2 src_size) +fragment_main(float2 texcoord: TEXCOORD) : SV_Target { float4 s00, s10, s01, s11; - float2 texel_size = 1.0 / src_size; + float2 texel_size = 1.0 / uniforms.src_size; // Use Slang target switches to dynamically compile for specific backend features __target_switch { diff --git a/kitty/shaders/slang.py b/kitty/shaders/slang.py index 7034b698f..7e804feef 100644 --- a/kitty/shaders/slang.py +++ b/kitty/shaders/slang.py @@ -1356,6 +1356,22 @@ def check_binding_slot(name: str, slot: int) -> int: return slot +# The uniform parameters of every program are declared as a single struct, +# shared by all the stages of the program, in a push constant block: +# +# struct Params { float4 src_rect; float extra_alpha; ... }; +# [[vk::push_constant]] ConstantBuffer uniforms; +# +# rather than as uniform parameters of the entry points. Slang lays out the +# uniform parameters of each entry point starting at offset zero, so the +# vertex and fragment parameters would overlap, which Vulkan does not allow in +# push constants. A single block shared by all stages is also what Metal wants, +# where it is passed with set{Vertex,Fragment}Bytes(), and it is emitted as +# loose uniforms for OpenGL. Vulkan guarantees only this many bytes of push +# constants. +PUSH_CONSTANTS_MAX_SIZE = 128 + + _PARAM_SCALARS = MappingProxyType({'float32': 'float', 'int32': 'int', 'uint32': 'uint', 'bool': 'bool'}) @@ -1393,8 +1409,8 @@ def program_metadata(target: ShaderTarget, reflections: Sequence[dict[str, Any]] inputs: dict[str, int] = {} textures: dict[str, int] = {} blocks: dict[str, dict[str, Any]] = {} - # Parameter blocks are the uniform parameters of each entry point and the - # pipeline constant blocks. kitty sets their contents with set_params() + # Parameter blocks are the push constant block holding the uniform + # parameters of the program and the pipeline constant blocks. kitty sets their contents with set_params() # rather than via uniform buffers. param_blocks: dict[str, dict[str, Any]] = {} # Uniform blocks that are emitted as uniform blocks rather than as loose uniforms by the target @@ -1403,6 +1419,17 @@ def program_metadata(target: ShaderTarget, reflections: Sequence[dict[str, Any]] for p in refl['parameters']: t = p['type'] match t['kind']: + case 'constantBuffer' if p['binding']['kind'] == 'pushConstantBuffer': + evl = t['elementVarLayout'] + size = evl['binding']['size'] + if size > PUSH_CONSTANTS_MAX_SIZE: + raise ValueError(f'The uniform parameters of the shader are {size} bytes, more than the maximum of {PUSH_CONSTANTS_MAX_SIZE}') + param_blocks['push_constants'] = { + 'name': '', + 'slot': -1, + 'size': size, + 'fields': [param_field(f['name'], f['binding']['offset'], f['type']) for f in evl['type']['fields']], + } case 'constantBuffer': evl = t['elementVarLayout'] et = evl['type'] @@ -1411,7 +1438,6 @@ def program_metadata(target: ShaderTarget, reflections: Sequence[dict[str, Any]] if tname in PIPELINE_CONSTANT_BLOCKS: param_blocks[tname] = { 'name': tname, - 'stage': '', 'slot': slot, 'size': evl['binding']['size'], 'fields': [param_field(f['name'], f['binding']['offset'], f['type']) for f in et['fields']], @@ -1431,8 +1457,6 @@ def program_metadata(target: ShaderTarget, reflections: Sequence[dict[str, Any]] raise ValueError(f'Unsupported shader parameter: {p["name"]} of kind: {t["kind"]}') for ep in refl['entryPoints']: stage = ep['stage'] - fields: list[dict[str, Any]] = [] - size = 0 for p in ep.get('parameters', ()): b = p.get('binding') or {} match b.get('kind'): @@ -1440,10 +1464,10 @@ def program_metadata(target: ShaderTarget, reflections: Sequence[dict[str, Any]] if stage == 'vertex': inputs[p['name']] = b['index'] case 'uniform': - fields.append(param_field(p['name'], b['offset'], p['type'])) - size = max(size, b['offset'] + b['size']) - if fields: - param_blocks[stage] = {'name': '', 'stage': stage, 'slot': -1, 'size': size, 'fields': fields} + raise ValueError( + f'The {stage} entry point has the uniform parameter: {p["name"]}, uniform parameters must be declared' + ' in a push constant block, see PUSH_CONSTANTS_MAX_SIZE' + ) native_names = {k: v.partition('[')[0] for k, v in native.loose_uniforms.items()} # ] native_names.update(native.uniform_struct_names) native_names.update(native.native_inputs) @@ -2257,16 +2281,21 @@ VertexOutput vmain_wrap(uint vertex_id : SV_VertexID) { return {float2(c[0], c[1]), float4(c[2], c[3], 0, 1)}; } +// The uniform parameters of the program, see PUSH_CONSTANTS_MAX_SIZE in slang.py +struct Params { + int group; + float4 viewport; + float animation_progress; + bool convert_to_srgb; + uint active_groups; +}; +[[vk::push_constant]] +ConstantBuffer uniforms; + [shader("fragment")] -float4 fmain_wrap( - float2 texcoord : TEXCOORD, - uniform int group, - uniform float4 viewport, - uniform float animation_progress, - uniform bool convert_to_srgb, - uniform uint active_groups -) : SV_Target { - return pipeline_fragment_main(texcoord, group, viewport, animation_progress, convert_to_srgb, active_groups); +float4 fmain_wrap(float2 texcoord : TEXCOORD) : SV_Target { + return pipeline_fragment_main( + texcoord, uniforms.group, uniforms.viewport, uniforms.animation_progress, uniforms.convert_to_srgb, uniforms.active_groups); } """.replace('MODULE', slot.replace('-', '_')).encode() diff --git a/kitty/shaders/tint.slang b/kitty/shaders/tint.slang index 1893c1a74..a5bdb3e33 100644 --- a/kitty/shaders/tint.slang +++ b/kitty/shaders/tint.slang @@ -2,19 +2,25 @@ // Copyright (C) 2026 Kovid Goyal // Distributed under terms of the GPLv3 license. +// 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 edges; // [ left, top, right, bottom ] + float4 tint_color; +}; +[[vk::push_constant]] +ConstantBuffer uniforms; + // Main Vertex Shader Entry Point [shader("vertex")] float4 -vertex_main( - uint vertex_id: SV_VertexID, - uniform float4 edges, // [ left, top, right, bottom ] - ) +vertex_main(uint vertex_id: SV_VertexID) : SV_Position { // Extract boundaries from the edges vector - float left = edges[0]; - float top = edges[1]; - float right = edges[2]; - float bottom = edges[3]; + float left = uniforms.edges[0]; + float top = uniforms.edges[1]; + float right = uniforms.edges[2]; + float bottom = uniforms.edges[3]; // Static mapping table for vertex positions const float2 pos_map[4] = { float2(left, top), float2(left, bottom), float2(right, bottom), float2(right, top) }; @@ -25,7 +31,7 @@ vertex_main( [shader("fragment")] float4 -fragment_main(uniform float4 tint_color) +fragment_main() : SV_Target { - return tint_color; + return uniforms.tint_color; } diff --git a/kitty/shaders/trail.slang b/kitty/shaders/trail.slang index d47a0dea0..45912f0dc 100644 --- a/kitty/shaders/trail.slang +++ b/kitty/shaders/trail.slang @@ -2,6 +2,19 @@ // Copyright (C) 2026 Kovid Goyal // Distributed under terms of the GPLv3 license. +// 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 x_coords; + float4 y_coords; + float2 cursor_edge_x; + float2 cursor_edge_y; + float3 trail_color; + float trail_opacity; +}; +[[vk::push_constant]] +ConstantBuffer uniforms; + struct VertexOutput { float2 frag_pos : TEXCOORD; float4 position : SV_Position; @@ -10,9 +23,9 @@ struct VertexOutput { // Main Vertex Shader Entry Point [shader("vertex")] VertexOutput -vertex_main(uint vertex_id: SV_VertexID, uniform float4 x_coords, uniform float4 y_coords) { +vertex_main(uint vertex_id: SV_VertexID) { VertexOutput output; - float2 pos = float2(x_coords[vertex_id], y_coords[vertex_id]); + float2 pos = float2(uniforms.x_coords[vertex_id], uniforms.y_coords[vertex_id]); output.position = float4(pos, 1.0, 1.0); output.frag_pos = pos; return output; @@ -22,16 +35,16 @@ vertex_main(uint vertex_id: SV_VertexID, uniform float4 x_coords, uniform float4 // Main Fragment Shader Entry Point [shader("fragment")] float4 -fragment_main(float2 frag_pos: TEXCOORD, uniform float2 cursor_edge_x, uniform float2 cursor_edge_y, uniform float3 trail_color, uniform float trail_opacity) +fragment_main(float2 frag_pos: TEXCOORD) : SV_Target { - float opacity = trail_opacity; + float opacity = uniforms.trail_opacity; // Evaluate if the fragment falls inside the bounding box of the cursor - float in_x = step(cursor_edge_x[0], frag_pos.x) * step(frag_pos.x, cursor_edge_x[1]); - float in_y = step(cursor_edge_y[1], frag_pos.y) * step(frag_pos.y, cursor_edge_y[0]); + 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]); // Mask out opacity inside the active cursor area opacity *= 1.0f - (in_x * in_y); // Output color with premultiplied alpha formatting - return float4(trail_color * opacity, opacity); + return float4(uniforms.trail_color * opacity, opacity); } diff --git a/kitty_tests/slang.py b/kitty_tests/slang.py index d29e1161a..88af1b7a4 100644 --- a/kitty_tests/slang.py +++ b/kitty_tests/slang.py @@ -11,10 +11,12 @@ import sys import tempfile from unittest.mock import patch -from kitty.constants import gpu_driver_path, slangc +from kitty.constants import gpu_driver_path, shaders_dir, slangc from kitty.fast_data_types import gpu_shader_target, load_gpu_driver from kitty.shaders.slang import ( + PUSH_CONSTANTS_MAX_SIZE, EntryPoint, + GLSLMetadata, LoadShaderPrograms, ShaderTarget, SlangFile, @@ -35,6 +37,7 @@ from kitty.shaders.slang import ( parse_var_directive, pipeline_definition, pointer_map_shaders, + program_metadata, slangc_version, text_contrast_is_identity, topological_layers, @@ -55,6 +58,59 @@ def driver_shader_target() -> ShaderTarget: class TestSlang(BaseTest): + def test_program_params(self): + # The uniform parameters of every built-in program are in a single + # push constant block shared by all stages, see PUSH_CONSTANTS_MAX_SIZE + target = driver_shader_target() + tdir = os.path.join(shaders_dir, target.id) + names = [x for x in os.listdir(tdir) if x.endswith('.json')] + self.assertTrue(names, f'No compiled shaders in {tdir}') + for name in names: + with open(os.path.join(tdir, name)) as f: + m = json.load(f) + push = [b for b in m['param_blocks'] if b['slot'] < 0] + self.assertLessEqual(len(push), 1, name) + for b in push: + self.assertFalse(b['name'], name) + self.assertLessEqual(b['size'], PUSH_CONSTANTS_MAX_SIZE, name) + for b in m['param_blocks']: + self.assertNotIn('stage', b, name) + if 'trail.json' in names: + with open(os.path.join(tdir, 'trail.json')) as f: + m = json.load(f) + (push,) = (b for b in m['param_blocks'] if b['slot'] < 0) + self.assertEqual({'x_coords', 'y_coords', 'cursor_edge_x', 'cursor_edge_y', 'trail_color', 'trail_opacity'}, {f['name'] for f in push['fields']}) + + def field(name: str, offset: int) -> dict: + t = {'kind': 'vector', 'elementCount': 4, 'elementType': {'kind': 'scalar', 'scalarType': 'float32'}} + return {'name': name, 'type': t, 'binding': {'kind': 'uniform', 'offset': offset, 'size': 16}} + + def push_block(size: int) -> dict: + fields = [field(f'f{i}', 16 * i) for i in range(size // 16)] + return { + 'name': 'uniforms', + 'binding': {'kind': 'pushConstantBuffer', 'index': 0}, + 'type': { + 'kind': 'constantBuffer', + 'elementVarLayout': { + 'type': {'kind': 'struct', 'name': 'Params', 'fields': fields}, + 'binding': {'kind': 'uniform', 'offset': 0, 'size': size}, + }, + }, + } + + refl = {'parameters': [push_block(32)], 'entryPoints': [{'name': 'vertex_main', 'stage': 'vertex', 'parameters': []}]} + m = program_metadata(target, [refl, refl], GLSLMetadata()) + self.assertEqual(1, len(m['param_blocks'])) + self.assertEqual(['f0', 'f1'], [f['name'] for f in m['param_blocks'][0]['fields']]) + # Too large for push constants + with self.assertRaises(ValueError): + program_metadata(target, [{'parameters': [push_block(PUSH_CONSTANTS_MAX_SIZE + 16)], 'entryPoints': []}], GLSLMetadata()) + # Uniform parameters of entry points are not allowed + refl = {'parameters': [], 'entryPoints': [{'name': 'vertex_main', 'stage': 'vertex', 'parameters': [field('x', 0)]}]} + with self.assertRaises(ValueError): + program_metadata(target, [refl], GLSLMetadata()) + def test_animation_step_parsing(self): def step(val): return parse_pipeline_definition(['startgroup', f'animation_step {val}', 'shaders focus-highlight', 'endgroup'], 'test')['groups'][0][