chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
1134 files changed
+433629
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,30 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
module alpha_blend;
|
||||
|
||||
// Alpha blend two colors returning the resulting color pre-multiplied by its alpha
|
||||
// and its alpha. See https://en.wikipedia.org/wiki/Alpha_compositing
|
||||
public float4
|
||||
alpha_blend(float4 over, float4 under) {
|
||||
float alpha = lerp(under.a, 1.0f, over.a);
|
||||
float3 combined_color = lerp(under.rgb * under.a, over.rgb, over.a);
|
||||
return float4(combined_color, alpha);
|
||||
}
|
||||
|
||||
// Same as alpha_blend() except that it assumes over and under are both premultiplied.
|
||||
public float4
|
||||
alpha_blend_premul(float4 over, float4 under) {
|
||||
float inv_over_alpha = 1.0f - over.a;
|
||||
float alpha = over.a + under.a * inv_over_alpha;
|
||||
return float4(over.rgb + under.rgb * inv_over_alpha, alpha);
|
||||
}
|
||||
|
||||
// Same as alpha_blend_premul with under_alpha = 1 outputs a blended color
|
||||
// with alpha 1 which is effectively pre-multiplied since alpha is 1
|
||||
public float4
|
||||
alpha_blend_premul(float4 over, float3 under) {
|
||||
float inv_over_alpha = 1.0f - over.a;
|
||||
return float4(over.rgb + under.rgb * inv_over_alpha, 1.0f);
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
// https://github.com/shader-slang/slang/issues/11874
|
||||
// warnings-disable: 41012
|
||||
|
||||
module background;
|
||||
|
||||
import utils;
|
||||
|
||||
#define NUM_COLORS 256
|
||||
|
||||
// Inputs {{{
|
||||
public struct CellRenderData {
|
||||
// Colors that are the same for every cell in the draw, converted to linear
|
||||
// space on the CPU so that the vertex shader does not have to do a gamma
|
||||
// LUT lookup for them once per vertex. Only rgb is used, they are float4
|
||||
// rather than float3 so that the C struct mirroring this one can use a
|
||||
// plain float[4] for each: in std140 a float3 is 16 byte aligned but only
|
||||
// 12 bytes in size, so a trailing one is not followed by any padding.
|
||||
// They come first so that everything after them stays tightly packed.
|
||||
public float4 default_fg_lin, default_bg_lin, highlight_fg_lin, highlight_bg_lin;
|
||||
public float4 main_cursor_fg_lin, main_cursor_bg_lin, url_color_lin;
|
||||
// The COLOR_IS_RGB/COLOR_IS_INDEX value for the extra cursor colors, zero
|
||||
// for the other color types which do not use it.
|
||||
public float4 extra_cursor_fg_lin, extra_cursor_bg_lin;
|
||||
|
||||
public float use_cell_bg_for_selection_fg, use_cell_fg_for_selection_fg, use_cell_for_selection_bg;
|
||||
|
||||
// default_fg and bg_colors0 are also needed as integers, to resolve cell
|
||||
// colors and to detect cells using the default background.
|
||||
public uint default_fg, url_style, inverted, main_cursor_is_special, extra_cursor_fg, extra_cursor_bg;
|
||||
|
||||
public uint columns, lines, sprites_xnum, sprites_ynum, cursor_shape, cell_width, cell_height;
|
||||
public uint cursor_x1, cursor_x2, cursor_y1, cursor_y2;
|
||||
public float cursor_opacity, inactive_text_alpha, fg_override_threshold, row_offset, dim_opacity, blink_opacity;
|
||||
|
||||
// must have unique entries with 0 being default_bg and unset being UINT32_MAX
|
||||
public uint bg_colors0, bg_colors1, bg_colors2, bg_colors3, bg_colors4, bg_colors5, bg_colors6, bg_colors7;
|
||||
public float bg_opacities0, bg_opacities1, bg_opacities2, bg_opacities3, bg_opacities4, bg_opacities5, bg_opacities6, bg_opacities7;
|
||||
};
|
||||
|
||||
// Uniform Blocks (adjust binding slots as needed for your pipeline layout)
|
||||
public ConstantBuffer<CellRenderData> crd;
|
||||
|
||||
// The SGR color table, then the mark background and foreground colors and
|
||||
// finally the special colors used by indexed color images.
|
||||
#define INDEXED_IMAGE_SPECIAL_COLORS_OFFSET (NUM_COLORS + MARK_MASK + MARK_MASK + 2)
|
||||
public struct ColorTable {
|
||||
uint color_table[INDEXED_IMAGE_SPECIAL_COLORS_OFFSET + NUM_INDEXED_IMAGE_SPECIAL_COLORS];
|
||||
};
|
||||
|
||||
public ConstantBuffer<ColorTable> ctb;
|
||||
#define color_table ctb.color_table
|
||||
|
||||
// The gamma LUT is a compile time constant and, unlike every other block
|
||||
// here, it is emitted into the default uniform block for OpenGL rather than
|
||||
// into a UBO, see GLSL_LOOSE_UNIFORM_BLOCKS in slang.py for why.
|
||||
public struct GammaLUT {
|
||||
float gamma_lut[256];
|
||||
};
|
||||
|
||||
public ConstantBuffer<GammaLUT> glt;
|
||||
#define gamma_lut glt.gamma_lut
|
||||
//
|
||||
|
||||
static const int fg_index_map[3] = { 0, 1, 0 };
|
||||
static const uint2 cell_pos_map[4] = {
|
||||
uint2(1u, 0u), // right, top
|
||||
uint2(1u, 1u), // right, bottom
|
||||
uint2(0u, 1u), // left, bottom
|
||||
uint2(0u, 0u) // left, top
|
||||
};
|
||||
static const uint cursor_shape_map[] = {
|
||||
// maps cursor shape to foreground sprite index
|
||||
0u, // NO_CURSOR
|
||||
0u, // BLOCK (this is rendered as background)
|
||||
2u, // BEAM
|
||||
3u, // UNDERLINE
|
||||
4u // UNFOCUSED
|
||||
};
|
||||
|
||||
// }}}
|
||||
|
||||
// Utility functions {{{
|
||||
|
||||
public static const uint BYTE_MASK = 0xFF;
|
||||
public static const uint BIT_MASK = 1u;
|
||||
// Linear space luminance values
|
||||
public static const float3 Y = float3(0.2126, 0.7152, 0.0722);
|
||||
|
||||
public float3
|
||||
color_to_vec(uint c) {
|
||||
uint r, g, b;
|
||||
r = (c >> 16) & BYTE_MASK;
|
||||
g = (c >> 8) & BYTE_MASK;
|
||||
b = c & BYTE_MASK;
|
||||
return float3(gamma_lut[r], gamma_lut[g], gamma_lut[b]);
|
||||
}
|
||||
|
||||
// Convert an entry in the palette of indexed color images to a linear color.
|
||||
// The palette is the SGR color table with its last few entries replaced by
|
||||
// special colors such as the default foreground and background.
|
||||
public float3
|
||||
indexed_image_color(uint idx) {
|
||||
const uint first_special = NUM_COLORS - NUM_INDEXED_IMAGE_SPECIAL_COLORS;
|
||||
idx &= BYTE_MASK;
|
||||
const uint slot = idx < first_special ? idx : idx + (INDEXED_IMAGE_SPECIAL_COLORS_OFFSET - first_special);
|
||||
return color_to_vec(color_table[slot]);
|
||||
}
|
||||
|
||||
public float
|
||||
one_if_equal_zero_otherwise(float a, float b) {
|
||||
return (1.0f - zero_or_one(abs(float(a) - float(b))));
|
||||
}
|
||||
|
||||
// We need an integer variant to accommodate GPU driver bugs, see
|
||||
// https://github.com/kovidgoyal/kitty/issues/9072
|
||||
public uint
|
||||
one_if_equal_zero_otherwise(int a, int b) {
|
||||
return (1u - uint(zero_or_one(abs(float(a) - float(b)))));
|
||||
}
|
||||
|
||||
public uint
|
||||
one_if_equal_zero_otherwise(uint a, uint b) {
|
||||
return (1u - uint(zero_or_one(abs(float(a) - float(b)))));
|
||||
}
|
||||
|
||||
public uint
|
||||
resolve_color(uint c, uint defval) {
|
||||
int t = int(c & BYTE_MASK);
|
||||
uint is_one = one_if_equal_zero_otherwise(t, 1);
|
||||
uint is_two = one_if_equal_zero_otherwise(t, 2);
|
||||
uint is_neither_one_nor_two = 1u - is_one - is_two;
|
||||
return is_one * color_table[(c >> 8) & BYTE_MASK] + is_two * (c >> 8) + is_neither_one_nor_two * defval;
|
||||
}
|
||||
|
||||
public float3
|
||||
to_color(uint c, uint defval) {
|
||||
return color_to_vec(resolve_color(c, defval));
|
||||
}
|
||||
|
||||
[ForceInline]
|
||||
float3
|
||||
q_func(float type_val, uint which, float3 val) {
|
||||
return one_if_equal_zero_otherwise(type_val, float(which)) * val;
|
||||
}
|
||||
|
||||
// resolved is color_to_vec() of c itself for COLOR_IS_RGB and of its color
|
||||
// table entry for COLOR_IS_INDEX, computed on the CPU since c is constant for
|
||||
// the whole draw. It is unused, and zero, for the other two color types.
|
||||
float3
|
||||
resolve_dynamic_color(uint c, float3 resolved, float3 special_val, float3 defval) {
|
||||
float type_val = float((c >> 24) & BYTE_MASK);
|
||||
return (
|
||||
q_func(type_val, COLOR_IS_RGB, resolved) + q_func(type_val, COLOR_IS_INDEX, resolved) + q_func(type_val, COLOR_IS_SPECIAL, special_val) +
|
||||
q_func(type_val, COLOR_NOT_SET, defval));
|
||||
}
|
||||
|
||||
public float
|
||||
contrast_ratio(float under_luminance, float over_luminance) {
|
||||
return clamp((max(under_luminance, over_luminance) + 0.05f) / (min(under_luminance, over_luminance) + 0.05f), 1.f, 21.f);
|
||||
}
|
||||
|
||||
public float
|
||||
contrast_ratio(float3 a, float3 b) {
|
||||
return contrast_ratio(dot(a, Y), dot(b, Y));
|
||||
}
|
||||
|
||||
public struct ColorPair {
|
||||
public float3 bg, fg;
|
||||
};
|
||||
|
||||
float
|
||||
contrast_ratio(ColorPair a) {
|
||||
return contrast_ratio(a.bg, a.fg);
|
||||
}
|
||||
|
||||
ColorPair
|
||||
if_less_than_pair(float a, float b, ColorPair thenval, ColorPair elseval) {
|
||||
return ColorPair(if_less_than(a, b, thenval.bg, elseval.bg), if_less_than(a, b, thenval.fg, elseval.fg));
|
||||
}
|
||||
|
||||
ColorPair
|
||||
if_one_then_pair(float condition, ColorPair thenval, ColorPair elseval) {
|
||||
return ColorPair(if_one_then(condition, thenval.bg, elseval.bg), if_one_then(condition, thenval.fg, elseval.fg));
|
||||
}
|
||||
|
||||
ColorPair
|
||||
resolve_extra_cursor_colors_for_special_cursor(float3 cell_bg, float3 cell_fg) {
|
||||
ColorPair cell = ColorPair(cell_fg, cell_bg);
|
||||
ColorPair base = ColorPair(crd.default_fg_lin.rgb, crd.default_bg_lin.rgb);
|
||||
float cr = contrast_ratio(cell);
|
||||
float br = contrast_ratio(base);
|
||||
ColorPair higher_contrast_pair = if_less_than_pair(cr, br, base, cell);
|
||||
return if_less_than_pair(cr, 2.5f, higher_contrast_pair, cell);
|
||||
}
|
||||
|
||||
ColorPair
|
||||
resolve_extra_cursor_colors(float3 cell_bg, float3 cell_fg, ColorPair main_cursor) {
|
||||
ColorPair ans = ColorPair(
|
||||
resolve_dynamic_color(crd.extra_cursor_bg, crd.extra_cursor_bg_lin.rgb, main_cursor.bg, main_cursor.bg),
|
||||
resolve_dynamic_color(crd.extra_cursor_fg, crd.extra_cursor_fg_lin.rgb, cell_bg, main_cursor.fg));
|
||||
ColorPair special = resolve_extra_cursor_colors_for_special_cursor(cell_bg, cell_fg);
|
||||
return if_one_then_pair(zero_or_one(abs(float((crd.extra_cursor_bg >> 24) & BYTE_MASK) - float(COLOR_IS_SPECIAL))), ans, special);
|
||||
}
|
||||
|
||||
uint
|
||||
is_cursor(uint x, uint y) {
|
||||
uint clamped_x = clamp(x, crd.cursor_x1, crd.cursor_x2);
|
||||
uint clamped_y = clamp(y, crd.cursor_y1, crd.cursor_y2);
|
||||
return one_if_equal_zero_otherwise(x, clamped_x) * one_if_equal_zero_otherwise(y, clamped_y);
|
||||
}
|
||||
|
||||
float
|
||||
background_opacity_for(uint bg, uint colorval, float opacity_if_matched) {
|
||||
float not_matched = step(1.0, abs(float(colorval) - float(bg)));
|
||||
return not_matched + opacity_if_matched * (1.0 - not_matched);
|
||||
}
|
||||
|
||||
float
|
||||
calc_background_opacity(uint bg) {
|
||||
return (
|
||||
background_opacity_for(bg, crd.bg_colors0, crd.bg_opacities0) * background_opacity_for(bg, crd.bg_colors1, crd.bg_opacities1) *
|
||||
background_opacity_for(bg, crd.bg_colors2, crd.bg_opacities2) * background_opacity_for(bg, crd.bg_colors3, crd.bg_opacities3) *
|
||||
background_opacity_for(bg, crd.bg_colors4, crd.bg_opacities4) * background_opacity_for(bg, crd.bg_colors5, crd.bg_opacities5) *
|
||||
background_opacity_for(bg, crd.bg_colors6, crd.bg_opacities6) * background_opacity_for(bg, crd.bg_colors7, crd.bg_opacities7));
|
||||
}
|
||||
// }}}
|
||||
|
||||
public struct CellData {
|
||||
public float has_cursor;
|
||||
public float has_block_cursor;
|
||||
public float reverse_video_cursor;
|
||||
public uint2 pos;
|
||||
public uint cursor_fg_sprite_idx;
|
||||
public ColorPair cursor;
|
||||
};
|
||||
|
||||
// The complete per-cell background computation, shared by the cell shader and
|
||||
// the padding shader. It computes the cell position and the final background
|
||||
// color (accounting for marks, reverse video, selection and the block cursor),
|
||||
// plus the intermediate data the cell foreground pass needs.
|
||||
public struct BackgroundOutput {
|
||||
public float4 position;
|
||||
public float3 background_rgb; // final background color (linear, post cursor/selection)
|
||||
public float bg_alpha; // final alpha, post special-cell opacity (pre draw_bg_bitfield mask)
|
||||
public float cell_has_default_bg;
|
||||
public float3 bg; // original background color, pre selection/cursor (used for selection fg)
|
||||
public float3 foreground; // resolved foreground color, pre selection/override
|
||||
public uint fg_as_uint;
|
||||
public uint text_attrs;
|
||||
public uint is_reversed;
|
||||
public CellData cell_data;
|
||||
};
|
||||
|
||||
public BackgroundOutput
|
||||
compute_background(uint3 colors, uint2 sprite_idx, uint is_selected, uint instance_id, uint vertex_id) {
|
||||
BackgroundOutput bo;
|
||||
|
||||
// set cell color indices {{{
|
||||
uint2 default_colors = uint2(crd.default_fg, crd.bg_colors0);
|
||||
uint text_attrs = sprite_idx[1];
|
||||
uint is_reversed = ((text_attrs >> REVERSE_SHIFT) & BIT_MASK);
|
||||
uint is_inverted = is_reversed + crd.inverted;
|
||||
int fg_index = fg_index_map[is_inverted];
|
||||
int bg_index = 1 - fg_index;
|
||||
int mark = int(text_attrs >> MARK_SHIFT) & MARK_MASK;
|
||||
uint has_mark = uint(step(1, float(mark)));
|
||||
uint bg_as_uint = resolve_color(colors[bg_index], default_colors[bg_index]);
|
||||
bg_as_uint = has_mark * color_table[NUM_COLORS + mark - 1] + (BIT_MASK - has_mark) * bg_as_uint;
|
||||
float cell_has_default_bg = 1.f - step(1.f, abs(float(bg_as_uint - crd.bg_colors0))); // 1 if has default bg else 0
|
||||
float3 bg = color_to_vec(bg_as_uint);
|
||||
float3 cell_bg = bg; // preserve original bg for the selection foreground color
|
||||
uint fg_as_uint = resolve_color(colors[fg_index], default_colors[fg_index]);
|
||||
fg_as_uint = has_mark * color_table[NUM_COLORS + MARK_MASK + mark] + (1u - has_mark) * fg_as_uint;
|
||||
float3 foreground = color_to_vec(fg_as_uint);
|
||||
// }}}
|
||||
|
||||
// Cell position {{{
|
||||
float dx = 2.0 / float(crd.columns);
|
||||
float dy = 2.0 / float(crd.lines);
|
||||
|
||||
// The current cell being rendered
|
||||
uint row = instance_id / crd.columns;
|
||||
uint column = instance_id - row * crd.columns;
|
||||
|
||||
// The position of this vertex, at a corner of the cell
|
||||
float left = -1.0 + float(column) * dx;
|
||||
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);
|
||||
bo.position = float4(select_x[pos.x], select_y[pos.y], 0.0, 1.0);
|
||||
// }}}
|
||||
|
||||
// Cursor shape and colors {{{
|
||||
float has_main_cursor = float(is_cursor(column, row));
|
||||
float multicursor_shape = float((is_selected >> 2) & 3u);
|
||||
float multicursor_uses_main_cursor_shape = float((is_selected >> 4) & BIT_MASK);
|
||||
multicursor_shape = if_one_then(multicursor_uses_main_cursor_shape, crd.cursor_shape, multicursor_shape);
|
||||
|
||||
float final_cursor_shape = if_one_then(has_main_cursor, crd.cursor_shape, multicursor_shape);
|
||||
float has_cursor = zero_or_one(final_cursor_shape);
|
||||
float is_block_cursor = has_cursor * one_if_equal_zero_otherwise(final_cursor_shape, 1.0);
|
||||
|
||||
ColorPair main_cursor;
|
||||
main_cursor.bg = crd.main_cursor_bg_lin.rgb;
|
||||
main_cursor.fg = crd.main_cursor_fg_lin.rgb;
|
||||
|
||||
float has_dim = float((text_attrs >> DIM_SHIFT) & BIT_MASK);
|
||||
float3 displayed_foreground = if_one_then(has_dim, lerp(cell_bg, foreground, crd.dim_opacity), foreground);
|
||||
ColorPair extra_cursor = resolve_extra_cursor_colors(cell_bg, displayed_foreground, main_cursor);
|
||||
ColorPair cursor = if_one_then_pair(has_main_cursor, main_cursor, extra_cursor);
|
||||
|
||||
uint extra_cursor_bg_type = (crd.extra_cursor_bg >> 24) & BYTE_MASK;
|
||||
uint extra_cursor_fg_type = (crd.extra_cursor_fg >> 24) & BYTE_MASK;
|
||||
float explicit_extra_reverse_video = float(one_if_equal_zero_otherwise(extra_cursor_bg_type, COLOR_IS_SPECIAL));
|
||||
float inherited_reverse_video = float(crd.main_cursor_is_special) * float(one_if_equal_zero_otherwise(extra_cursor_bg_type, COLOR_NOT_SET)) *
|
||||
float(one_if_equal_zero_otherwise(extra_cursor_fg_type, COLOR_NOT_SET));
|
||||
|
||||
CellData cell_data;
|
||||
cell_data.has_cursor = has_cursor;
|
||||
cell_data.has_block_cursor = is_block_cursor;
|
||||
cell_data.reverse_video_cursor =
|
||||
if_one_then(has_main_cursor, float(crd.main_cursor_is_special), max(explicit_extra_reverse_video, inherited_reverse_video));
|
||||
cell_data.pos = pos;
|
||||
cell_data.cursor_fg_sprite_idx = cursor_shape_map[int(final_cursor_shape)];
|
||||
cell_data.cursor = cursor;
|
||||
// }}}
|
||||
|
||||
// Background {{{
|
||||
float bg_alpha = calc_background_opacity(bg_as_uint);
|
||||
// we use max so that opacity of the block cursor cell background goes from bg_alpha to 1
|
||||
float effective_cursor_opacity = max(crd.cursor_opacity, bg_alpha);
|
||||
// is_special_cell is either 0 or 1
|
||||
float is_special_cell = cell_data.has_block_cursor + float(is_selected & BIT_MASK);
|
||||
is_special_cell += float(is_reversed); // reverse video cells should be opaque as well
|
||||
is_special_cell = zero_or_one(is_special_cell);
|
||||
cell_has_default_bg = if_one_then(is_special_cell, 0., cell_has_default_bg);
|
||||
|
||||
// special cells must always be fully opaque, otherwise leave bg_alpha untouched
|
||||
bg_alpha = if_one_then(is_special_cell, 1.f, bg_alpha);
|
||||
// Selection and cursor
|
||||
bg_alpha = if_one_then(cell_data.has_block_cursor, effective_cursor_opacity, bg_alpha);
|
||||
bg = if_one_then(float(is_selected & BIT_MASK), if_one_then(crd.use_cell_for_selection_bg, color_to_vec(fg_as_uint), crd.highlight_bg_lin.rgb), bg);
|
||||
float3 background_rgb = if_one_then(cell_data.has_block_cursor, lerp(bg, cell_data.cursor.bg, crd.cursor_opacity), bg);
|
||||
// }}}
|
||||
|
||||
bo.background_rgb = background_rgb;
|
||||
bo.bg_alpha = bg_alpha;
|
||||
bo.cell_has_default_bg = cell_has_default_bg;
|
||||
bo.bg = cell_bg;
|
||||
bo.foreground = foreground;
|
||||
bo.fg_as_uint = fg_as_uint;
|
||||
bo.text_attrs = text_attrs;
|
||||
bo.is_reversed = is_reversed;
|
||||
bo.cell_data = cell_data;
|
||||
return bo;
|
||||
}
|
||||
|
||||
// Return the premultiplied background color for a cell, used by the padding
|
||||
// shader to color padding regions to match their neighboring cell. This is the
|
||||
// same as the cell background pass but without the draw_bg_bitfield masking, so
|
||||
// the padding is always drawn. The premultiplied alpha ensures padding matches
|
||||
// its neighboring cell under a semi-transparent OS window.
|
||||
public float4
|
||||
padding_background_premul(uint3 colors, uint2 sprite_idx, uint is_selected, uint instance_id) {
|
||||
BackgroundOutput bo = compute_background(colors, sprite_idx, is_selected, instance_id, 0u);
|
||||
return vec4_premul(bo.background_rgb, bo.bg_alpha);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
import alpha_blend;
|
||||
|
||||
// Constants and Macros
|
||||
#define left 0
|
||||
#define top 1
|
||||
#define right 2
|
||||
#define bottom 3
|
||||
#define tex_left 0.0
|
||||
#define tex_top 0.0
|
||||
#define tex_right 1.0
|
||||
#define tex_bottom 1.0
|
||||
|
||||
#define x_axis 0
|
||||
#define y_axis 1
|
||||
|
||||
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) };
|
||||
|
||||
|
||||
struct VertexOutput {
|
||||
float2 texcoord : TEXCOORD;
|
||||
float4 position : SV_Position;
|
||||
};
|
||||
|
||||
// Helper Functions
|
||||
float
|
||||
scale_factor(float window_size, float image_size) {
|
||||
return window_size / image_size;
|
||||
}
|
||||
|
||||
float
|
||||
tiling_factor(int i, float4 sizes, float tiled) {
|
||||
int window = i;
|
||||
int image = i + 2;
|
||||
return tiled * scale_factor(sizes[window], sizes[image]) + (1.0 - 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, ) {
|
||||
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])
|
||||
};
|
||||
|
||||
|
||||
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.position = float4(pos_map[vertex_id], 0.0, 1.0);
|
||||
return output;
|
||||
}
|
||||
|
||||
// Global Texture Bindings
|
||||
uniform Sampler2D image;
|
||||
|
||||
// Main Fragment Shader Entry Point
|
||||
[shader("fragment")]
|
||||
float4
|
||||
fragment_main(float2 texcoord: TEXCOORD, uniform float4 background)
|
||||
: 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);
|
||||
return premult_color;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
// Maps a vertex id to src and destination co-ordinates
|
||||
module blit_common;
|
||||
|
||||
public struct BlitOutput {
|
||||
public float2 texcoord;
|
||||
public float2 position;
|
||||
};
|
||||
|
||||
#define left 0
|
||||
#define top 1
|
||||
#define right 2
|
||||
#define bottom 3
|
||||
|
||||
// Static constant array mapping vertex IDs
|
||||
static const int2 vertex_pos_map[4] = { { right, top }, { right, bottom }, { left, bottom }, { left, top } };
|
||||
|
||||
public BlitOutput
|
||||
get_coords_for_blit(uint vertex_id, float4 src_rect, float4 dest_rect) {
|
||||
int2 pos = vertex_pos_map[vertex_id];
|
||||
BlitOutput output;
|
||||
output.texcoord = float2(src_rect[pos.x], src_rect[pos.y]);
|
||||
output.position = float2(dest_rect[pos.x], dest_rect[pos.y]);
|
||||
return output;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
import blit_common;
|
||||
import alpha_blend;
|
||||
import utils;
|
||||
import linear2srgb;
|
||||
|
||||
struct VSOutput {
|
||||
float2 texcoord : TEXCOORD;
|
||||
float4 position : SV_Position;
|
||||
};
|
||||
|
||||
|
||||
[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);
|
||||
return { ans.texcoord, float4(ans.position[0], ans.position[1], 0.0, 1.0) };
|
||||
}
|
||||
|
||||
uniform Sampler2D image;
|
||||
|
||||
[shader("fragment")]
|
||||
float4
|
||||
fragment_main(float2 texcoord: TEXCOORD)
|
||||
: SV_Target {
|
||||
float4 color_premul = image.Sample(texcoord);
|
||||
return vec4_premul(linear2srgb(color_premul.rgb / color_premul.a), color_premul.a);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
import utils;
|
||||
|
||||
// Macro definitions
|
||||
#define DEFAULT_BG 0
|
||||
#define ACTIVE_BORDER_COLOR 1
|
||||
#define INACTIVE_BORDER_COLOR 2
|
||||
#define WINDOW_BACKGROUND_PLACEHOLDER 3
|
||||
#define BELL_BORDER_COLOR 4
|
||||
#define TAB_BAR_BG_COLOR 5
|
||||
#define TAB_BAR_MARGIN_COLOR 6
|
||||
#define TAB_BAR_EDGE_LEFT_COLOR 7
|
||||
#define TAB_BAR_EDGE_RIGHT_COLOR 8
|
||||
|
||||
// Emitted into the default uniform block for OpenGL rather than into a UBO,
|
||||
// see GLSL_LOOSE_UNIFORM_BLOCKS in slang.py for why.
|
||||
struct GammaLUT {
|
||||
uniform float gamma_lut[256];
|
||||
};
|
||||
ConstantBuffer<GammaLUT> glt;
|
||||
#define gamma_lut glt.gamma_lut
|
||||
|
||||
struct Colors {
|
||||
uniform uint colors[9];
|
||||
};
|
||||
ConstantBuffer<Colors> clrs;
|
||||
#define colors clrs.colors
|
||||
|
||||
// Vertex attributes matching GLSL input locations
|
||||
struct VertexInput {
|
||||
float4 rect; // left, top, right, bottom
|
||||
uint rect_color;
|
||||
};
|
||||
|
||||
// Vertex shader output structure
|
||||
struct VertexOutput {
|
||||
float4 color_premul : COLOR_PREMUL;
|
||||
float4 position : SV_Position;
|
||||
};
|
||||
|
||||
// Indices into the rect vector
|
||||
static const int LEFT = 0;
|
||||
static const int TOP = 1;
|
||||
static const int RIGHT = 2;
|
||||
static const int BOTTOM = 3;
|
||||
static const uint FF = 0xff;
|
||||
|
||||
static const uint2 pos_map[4] = { uint2(RIGHT, TOP), uint2(RIGHT, BOTTOM), uint2(LEFT, BOTTOM), uint2(LEFT, TOP) };
|
||||
|
||||
float
|
||||
to_color(uint c) {
|
||||
return gamma_lut[c & FF];
|
||||
}
|
||||
|
||||
float
|
||||
is_integer_value(uint c, int x) {
|
||||
return 1. - step(0.5, abs(float(c) - float(x)));
|
||||
}
|
||||
|
||||
float3
|
||||
as_color_vector(uint c, int shift) {
|
||||
return float3(to_color(c >> shift), to_color(c >> (shift - 8)), to_color(c >> (shift - 16)));
|
||||
}
|
||||
|
||||
[shader("vertex")]
|
||||
VertexOutput
|
||||
vertex_main(float4 rect, uint rect_color, uniform float background_opacity, uint vertex_id: SV_VertexID) {
|
||||
VertexOutput output;
|
||||
|
||||
uint2 pos = pos_map[vertex_id];
|
||||
output.position = float4(rect[pos.x], rect[pos.y], 0, 1);
|
||||
|
||||
float3 window_bg = as_color_vector(rect_color, 24);
|
||||
uint rc = rect_color & FF;
|
||||
float3 color3 = as_color_vector(colors[rc], 16);
|
||||
|
||||
float is_window_bg = is_integer_value(rc, WINDOW_BACKGROUND_PLACEHOLDER); // used by window padding areas
|
||||
float is_default_bg = is_integer_value(rc, DEFAULT_BG);
|
||||
color3 = if_one_then(is_window_bg, window_bg, color3);
|
||||
|
||||
// Actual border quads and tab bar edge strips must be always drawn opaque
|
||||
float is_not_a_border = zero_or_one(
|
||||
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.);
|
||||
output.color_premul = vec4_premul(color3, final_opacity);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
[shader("fragment")]
|
||||
float4
|
||||
fragment_main(float4 color_premul: COLOR_PREMUL)
|
||||
: SV_Target {
|
||||
return color_premul;
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
// https://github.com/shader-slang/slang/issues/11874
|
||||
// warnings-disable: 41012
|
||||
|
||||
import utils;
|
||||
import hsluv;
|
||||
import alpha_blend;
|
||||
import linear2srgb;
|
||||
import background;
|
||||
|
||||
extern static const uint FG_OVERRIDE_ALGO;
|
||||
extern static const bool TEXT_NEW_GAMMA;
|
||||
extern static const bool TEXT_CONTRAST_IDENTITY;
|
||||
extern static const uint RENDER_MODE;
|
||||
|
||||
static const bool ONLY_FOREGROUND = RENDER_MODE == 2;
|
||||
static const bool ONLY_BACKGROUND = RENDER_MODE == 1;
|
||||
|
||||
// The background color computation, the cell render data, color table and gamma
|
||||
// LUT as well as most color utility functions live in the background module so
|
||||
// that they can be shared with the padding shader.
|
||||
|
||||
uniform Sampler2D<uint4> sprite_decorations_map;
|
||||
|
||||
static const uint SPRITE_INDEX_MASK = 0x7fffffff;
|
||||
static const uint SPRITE_COLORED_MASK = 0x80000000;
|
||||
static const uint SPRITE_COLORED_SHIFT = 31u;
|
||||
// Set in underline_exclusion_pos when the glyph, decorations, and cursor sprite
|
||||
// are all 0. The block cursor is sprite 0 and its color is already in the
|
||||
// background. Packed into an existing flat varying to not use another slot.
|
||||
static const uint SKIP_TEXT_FLAG = 0x80000000u;
|
||||
|
||||
struct VertexOutput {
|
||||
float4 position : SV_Position;
|
||||
|
||||
float3 background;
|
||||
float4 effective_background_premul;
|
||||
float effective_text_alpha;
|
||||
float3 sprite_pos;
|
||||
float3 underline_pos;
|
||||
float3 cursor_pos;
|
||||
float3 strike_pos;
|
||||
nointerpolation uint underline_exclusion_pos; // has SKIP_TEXT_FLAG set for blank cells
|
||||
float3 cell_foreground;
|
||||
float4 cursor_color_premult;
|
||||
float3 decoration_fg;
|
||||
float colored_sprite;
|
||||
};
|
||||
|
||||
// Foreground utility functions {{{
|
||||
uint3
|
||||
to_sprite_coords(uint idx) {
|
||||
uint sprites_per_page = crd.sprites_xnum * crd.sprites_ynum;
|
||||
uint z = idx / sprites_per_page;
|
||||
uint num_on_last_page = idx - sprites_per_page * z;
|
||||
uint y = num_on_last_page / crd.sprites_xnum;
|
||||
uint x = num_on_last_page - crd.sprites_xnum * y;
|
||||
return uint3(x, y, z);
|
||||
}
|
||||
|
||||
float3
|
||||
to_sprite_pos(uint2 pos, uint idx) {
|
||||
uint3 c = to_sprite_coords(idx);
|
||||
float2 s_xpos = float2(float(c.x), float(c.x) + 1.0f) * (1.0f / float(crd.sprites_xnum));
|
||||
float2 s_ypos = float2(float(c.y), float(c.y) + 1.0f) * (1.0f / float(crd.sprites_ynum));
|
||||
uint texture_height_px = (crd.cell_height + 1u) * crd.sprites_ynum;
|
||||
float row_height = 1.0f / float(texture_height_px);
|
||||
s_ypos[1] -= row_height; // skip the decorations_exclude row
|
||||
return float3(s_xpos[pos.x], s_ypos[pos.y], float(c.z));
|
||||
}
|
||||
|
||||
uint
|
||||
to_underline_exclusion_pos(uint2 sprite_idx) {
|
||||
uint3 c = to_sprite_coords(sprite_idx[0]);
|
||||
uint cell_top_px = c.y * (crd.cell_height + 1u);
|
||||
return cell_top_px + crd.cell_height;
|
||||
}
|
||||
|
||||
uint
|
||||
read_sprite_decorations_idx(uint2 sprite_idx) {
|
||||
int idx = int(sprite_idx[0] & SPRITE_INDEX_MASK);
|
||||
int width, height;
|
||||
sprite_decorations_map.GetDimensions(width, height);
|
||||
int2 sz = int2(width, height);
|
||||
int y = idx / sz[0];
|
||||
int x = idx - y * sz[0];
|
||||
return sprite_decorations_map[int2(x, y)].r;
|
||||
}
|
||||
|
||||
uint2
|
||||
get_decorations_indices(uint2 sprite_idx, uint in_url /* [0, 1] */, uint text_attrs) {
|
||||
uint decorations_idx = read_sprite_decorations_idx(sprite_idx);
|
||||
uint has_decorations = uint(zero_or_one(float(decorations_idx)));
|
||||
uint strike_style = ((text_attrs >> STRIKE_SHIFT) & BIT_MASK); // 0 or 1
|
||||
uint strike_idx = decorations_idx * strike_style;
|
||||
uint underline_style = ((text_attrs >> DECORATION_SHIFT) & DECORATION_MASK);
|
||||
underline_style = in_url * crd.url_style + (1u - in_url) * underline_style; // [0, 5]
|
||||
uint has_underline = uint(step(0.5f, float(underline_style))); // [0, 1]
|
||||
return has_decorations * uint2(strike_idx, has_underline * (decorations_idx + underline_style));
|
||||
}
|
||||
// }}}
|
||||
|
||||
// Override foreground colors {{{
|
||||
float3
|
||||
fg_override_luminance(float colored_sprite, float under_luminance, float over_lumininace, float3 under, float3 over) {
|
||||
// If the difference in luminance is too small,
|
||||
// force the foreground color to be black or white.
|
||||
float diff_luminance = abs(under_luminance - over_lumininace);
|
||||
float override_level = (1.f - colored_sprite) * step(diff_luminance, crd.fg_override_threshold);
|
||||
float original_level = 1.f - override_level;
|
||||
return original_level * over + override_level * float3(step(under_luminance, 0.5f));
|
||||
}
|
||||
|
||||
float3
|
||||
fg_override_contrast(float under_luminance, float over_luminance, float3 under, float3 over) {
|
||||
float ratio = contrast_ratio(under_luminance, over_luminance);
|
||||
float3 diff = abs(under - over);
|
||||
float3 over_hsluv = rgbToHsluv(over);
|
||||
const float min_contrast_ratio = crd.fg_override_threshold;
|
||||
float target_lum_a = clamp((under_luminance + 0.05) * min_contrast_ratio - 0.05, 0.0, 1.0);
|
||||
float target_lum_b = clamp((under_luminance + 0.05) / min_contrast_ratio - 0.05, 0.0, 1.0);
|
||||
float3 result_a = clamp(hsluvToRgb(float3(over_hsluv.x, over_hsluv.y, target_lum_a * 100.0)), 0.0, 1.0);
|
||||
float3 result_b = clamp(hsluvToRgb(float3(over_hsluv.x, over_hsluv.y, target_lum_b * 100.0)), 0.0, 1.0);
|
||||
float result_a_ratio = contrast_ratio(under_luminance, dot(result_a, Y));
|
||||
float result_b_ratio = contrast_ratio(under_luminance, dot(result_b, Y));
|
||||
float3 result = lerp(result_a, result_b, step(result_a_ratio, result_b_ratio));
|
||||
float fallback_condition = max(step(diff.x + diff.y + diff.z, 0.001), step(min_contrast_ratio, ratio));
|
||||
return lerp(result, over, fallback_condition);
|
||||
}
|
||||
|
||||
float3
|
||||
override_foreground_color(float3 over, float3 under, float colored_sprite) {
|
||||
float under_luminance = dot(under, Y);
|
||||
float over_lumininace = dot(over.rgb, Y);
|
||||
if (FG_OVERRIDE_ALGO == 1) return fg_override_luminance(colored_sprite, under_luminance, over_lumininace, under, over);
|
||||
return fg_override_contrast(under_luminance, over_lumininace, under, over);
|
||||
}
|
||||
// }}}
|
||||
|
||||
[shader("vertex")]
|
||||
VertexOutput
|
||||
vertex_main(
|
||||
[[vk::location(0)]] uint3 colors,
|
||||
[[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, ) {
|
||||
VertexOutput vo;
|
||||
|
||||
BackgroundOutput bo = compute_background(colors, sprite_idx, is_selected, instance_id, vertex_id);
|
||||
vo.position = bo.position;
|
||||
float3 background_rgb = bo.background_rgb;
|
||||
float3 foreground = bo.foreground;
|
||||
uint fg_as_uint = bo.fg_as_uint;
|
||||
uint text_attrs = bo.text_attrs;
|
||||
CellData cell_data = bo.cell_data;
|
||||
|
||||
// Foreground {{{
|
||||
if (!ONLY_BACKGROUND) { // background does not depend on foreground
|
||||
// The character sprite being rendered
|
||||
vo.sprite_pos = to_sprite_pos(cell_data.pos, sprite_idx[0] & SPRITE_INDEX_MASK);
|
||||
vo.colored_sprite = float((sprite_idx[0] & SPRITE_COLORED_MASK) >> SPRITE_COLORED_SHIFT);
|
||||
|
||||
float has_dim = float((text_attrs >> DIM_SHIFT) & BIT_MASK), has_blink = float((text_attrs >> BLINK_SHIFT) & BIT_MASK);
|
||||
// A reverse video block cursor already uses the dimmed foreground as its text color, so fade out
|
||||
// the DIM alpha in step with the cursor opacity to avoid dimming twice without un-dimming a fading cursor
|
||||
float undim = cell_data.has_block_cursor * cell_data.reverse_video_cursor * crd.cursor_opacity;
|
||||
vo.effective_text_alpha =
|
||||
crd.inactive_text_alpha * if_one_then(has_dim, lerp(crd.dim_opacity, 1.0, undim), 1.0) * if_one_then(has_blink, crd.blink_opacity, 1.0);
|
||||
float in_url = float((is_selected >> 1) & BIT_MASK);
|
||||
vo.decoration_fg = if_one_then(in_url, crd.url_color_lin.rgb, to_color(colors[2], fg_as_uint));
|
||||
// Selection
|
||||
float3 selection_color = if_one_then(crd.use_cell_bg_for_selection_fg, bo.bg, crd.highlight_fg_lin.rgb);
|
||||
selection_color = if_one_then(crd.use_cell_fg_for_selection_fg, foreground, selection_color);
|
||||
foreground = if_one_then(float(is_selected & BIT_MASK), selection_color, foreground);
|
||||
vo.decoration_fg = if_one_then(float(is_selected & BIT_MASK), selection_color, vo.decoration_fg);
|
||||
// Underline and strike through (rendered via sprites)
|
||||
uint2 decs = get_decorations_indices(sprite_idx, uint(in_url), text_attrs);
|
||||
vo.strike_pos = to_sprite_pos(cell_data.pos, decs[0]);
|
||||
vo.underline_pos = to_sprite_pos(cell_data.pos, decs[1]);
|
||||
|
||||
// Cursor
|
||||
vo.cursor_color_premult = float4(cell_data.cursor.bg * crd.cursor_opacity, crd.cursor_opacity);
|
||||
float3 final_cursor_text_color = lerp(foreground, cell_data.cursor.fg, crd.cursor_opacity);
|
||||
foreground = if_one_then(cell_data.has_block_cursor, final_cursor_text_color, foreground);
|
||||
vo.decoration_fg = if_one_then(cell_data.has_block_cursor, final_cursor_text_color, vo.decoration_fg);
|
||||
uint cursor_sprite = cell_data.cursor_fg_sprite_idx * uint(cell_data.has_cursor);
|
||||
vo.cursor_pos = to_sprite_pos(cell_data.pos, cursor_sprite);
|
||||
uint skip_text = uint((sprite_idx[0] & SPRITE_INDEX_MASK) == 0u && decs[0] == 0u && decs[1] == 0u && cursor_sprite == 0u);
|
||||
vo.underline_exclusion_pos = to_underline_exclusion_pos(sprite_idx) | (skip_text * SKIP_TEXT_FLAG);
|
||||
}
|
||||
// }}}
|
||||
|
||||
vo.background = background_rgb;
|
||||
|
||||
if (!ONLY_BACKGROUND && FG_OVERRIDE_ALGO > 0) {
|
||||
vo.decoration_fg = override_foreground_color(vo.decoration_fg, background_rgb, vo.colored_sprite);
|
||||
foreground = override_foreground_color(foreground, background_rgb, vo.colored_sprite);
|
||||
}
|
||||
|
||||
if (!ONLY_FOREGROUND) {
|
||||
float4 bgpremul = vec4_premul(background_rgb, bo.bg_alpha);
|
||||
// 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));
|
||||
bgpremul *= draw_bg;
|
||||
vo.effective_background_premul = bgpremul;
|
||||
}
|
||||
|
||||
if (!ONLY_BACKGROUND) vo.cell_foreground = foreground;
|
||||
|
||||
return vo;
|
||||
}
|
||||
|
||||
uniform Sampler2DArray sprites;
|
||||
// Scaling factor for the extra text-alpha adjustment for luminance-difference.
|
||||
static const float text_gamma_scaling = 0.5;
|
||||
|
||||
float
|
||||
clamp_to_unit_float(float x) {
|
||||
// Clamp value to suitable output range
|
||||
return clamp(x, 0.0f, 1.0f);
|
||||
}
|
||||
|
||||
float4
|
||||
foreground_contrast_new(float4 over, float3 under, float text_contrast, float text_gamma_adjustment) {
|
||||
if (TEXT_CONTRAST_IDENTITY) return over;
|
||||
float under_luminance = dot(under, Y);
|
||||
float over_lumininace = dot(over.rgb, Y);
|
||||
// Apply additional gamma-adjustment scaled by the luminance difference, the darker the foreground the more adjustment we apply.
|
||||
// A multiplicative contrast is also available to increase saturation.
|
||||
over.a =
|
||||
clamp_to_unit_float(lerp(over.a, pow(over.a, text_gamma_adjustment), (1 - over_lumininace + under_luminance) * text_gamma_scaling) * text_contrast);
|
||||
return over;
|
||||
}
|
||||
|
||||
float4
|
||||
foreground_contrast_old(float4 over, float3 under) {
|
||||
// Simulation of gamma-incorrect blending
|
||||
float under_luminance = dot(under, Y);
|
||||
float over_lumininace = dot(over.rgb, Y);
|
||||
// This is the original gamma-incorrect rendering, it is the solution of the following equation:
|
||||
//
|
||||
// linear2srgb(over * overA2 + under * (1 - overA2)) = linear2srgb(over) * over.a + linear2srgb(under) * (1 - over.a)
|
||||
// ^ gamma correct blending with new alpha ^ gamma incorrect blending with old alpha
|
||||
over.a = clamp_to_unit_float(
|
||||
(srgb2linear(linear2srgb(over_lumininace) * over.a + linear2srgb(under_luminance) * (1.0f - over.a)) - under_luminance) /
|
||||
(over_lumininace - under_luminance));
|
||||
return over;
|
||||
}
|
||||
|
||||
float4
|
||||
foreground_contrast(float4 over, float3 under, float text_contrast, float text_gamma_adjustment) {
|
||||
if (TEXT_NEW_GAMMA) return foreground_contrast_new(over, under, text_contrast, text_gamma_adjustment);
|
||||
return foreground_contrast_old(over, under);
|
||||
}
|
||||
|
||||
float4
|
||||
load_text_foreground_color(float3 sprite_pos, float colored_sprite, float3 cell_foreground) {
|
||||
// For colored sprites use the color from the sprite rather than the text foreground
|
||||
// Return non-premultiplied foreground color
|
||||
float4 text_fg = sprites.SampleLevel(sprite_pos, 0);
|
||||
return float4(lerp(cell_foreground, text_fg.xyz, colored_sprite), text_fg.w);
|
||||
}
|
||||
|
||||
float4
|
||||
calculate_premul_foreground_from_sprites(
|
||||
float3 sprite_pos,
|
||||
float3 underline_pos,
|
||||
float3 cursor_pos,
|
||||
float3 strike_pos,
|
||||
uint underline_exclusion_pos,
|
||||
float4 text_fg,
|
||||
float3 decoration_fg,
|
||||
float4 cursor_color_premult,
|
||||
float effective_text_alpha, ) {
|
||||
// Return premul foreground color from decorations (cursor, underline, strikethrough)
|
||||
int width, height, layer;
|
||||
sprites.GetDimensions(width, height, layer);
|
||||
float3 sz = float3(float(width), float(height), float(layer));
|
||||
|
||||
float underline_alpha = sprites.SampleLevel(underline_pos, 0).w;
|
||||
int3 fetch_coord = int3(int(sprite_pos.x * sz.x), int(underline_exclusion_pos), int(sprite_pos.z));
|
||||
float underline_exclusion = sprites[fetch_coord].w;
|
||||
|
||||
underline_alpha *= 1.0 - underline_exclusion;
|
||||
float strike_alpha = sprites.SampleLevel(strike_pos, 0).w;
|
||||
float cursor_alpha = sprites.SampleLevel(cursor_pos, 0).w;
|
||||
|
||||
float combined_alpha = min(text_fg.w + strike_alpha, 1.0);
|
||||
|
||||
float4 ans = alpha_blend(float4(text_fg.rgb, combined_alpha * effective_text_alpha), float4(decoration_fg, underline_alpha * effective_text_alpha));
|
||||
|
||||
return lerp(ans, cursor_color_premult, cursor_alpha * cursor_color_premult.w);
|
||||
}
|
||||
|
||||
float4
|
||||
adjust_foreground_contrast_with_background(float4 text_fg, float3 bg, float text_contrast, float text_gamma_adjustment) {
|
||||
return foreground_contrast(text_fg, bg, text_contrast, text_gamma_adjustment);
|
||||
}
|
||||
|
||||
[shader("fragment")]
|
||||
float4
|
||||
fragment_main(VertexOutput vo, uniform float text_contrast, uniform float text_gamma_adjustment, )
|
||||
: SV_Target {
|
||||
float4 ans_premul = 0;
|
||||
if (!ONLY_FOREGROUND) ans_premul = vo.effective_background_premul;
|
||||
|
||||
// The sprite samples below use SampleLevel() as this branch is not uniform
|
||||
// across a 2x2 pixel quad at cell boundaries, so implicit derivatives would
|
||||
// be undefined. The sprites texture has no mipmaps, so LOD 0 is identical.
|
||||
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);
|
||||
float4 text_fg_premul = calculate_premul_foreground_from_sprites(
|
||||
vo.sprite_pos,
|
||||
vo.underline_pos,
|
||||
vo.cursor_pos,
|
||||
vo.strike_pos,
|
||||
vo.underline_exclusion_pos,
|
||||
text_fg,
|
||||
vo.decoration_fg,
|
||||
vo.cursor_color_premult,
|
||||
vo.effective_text_alpha);
|
||||
if (ONLY_FOREGROUND) ans_premul = text_fg_premul;
|
||||
else ans_premul = alpha_blend_premul(text_fg_premul, ans_premul);
|
||||
}
|
||||
return ans_premul;
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,67 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Original shader: https://gist.github.com/qwerasd205/c3da6c610c8ffe17d6d2d3cc7068f17f
|
||||
// Credits: https://github.com/qwerasd205
|
||||
// Bloom effect using golden spiral sample pattern.
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
// Golden spiral samples [x, y, weight] — weight is inverse of distance
|
||||
static const float3 samples[24] = {
|
||||
float3(0.1693761725038636, 0.9855514761735895, 1.0),
|
||||
float3(-1.333070830962943, 0.4721463328627773, 0.7071067811865475),
|
||||
float3(-0.8464394909806497, -1.51113870578065, 0.5773502691896258),
|
||||
float3(1.554155680728463, -1.2588090085709776, 0.5),
|
||||
float3(1.681364377589461, 1.4741145918052656, 0.4472135954999579),
|
||||
float3(-1.2795157692199817, 2.088741103228784, 0.4082482904638631),
|
||||
float3(-2.4575847530631187, -0.9799373355024756, 0.3779644730092272),
|
||||
float3(0.5874641440200847, -2.7667464429345077, 0.35355339059327373),
|
||||
float3(2.997715703369726, 0.11704939884745152, 0.3333333333333333),
|
||||
float3(0.41360842451688395, 3.1351121305574803, 0.31622776601683794),
|
||||
float3(-3.167149933769243, 0.9844599011770256, 0.30151134457776363),
|
||||
float3(-1.5736713846521535, -3.0860263079123245, 0.2886751345948129),
|
||||
float3(2.888202648340422, -2.1583061557896213, 0.2773500981126146),
|
||||
float3(2.7150778983300325, 2.5745586041105715, 0.2672612419124244),
|
||||
float3(-2.1504069972377464, 3.2211410627650165, 0.2581988897471611),
|
||||
float3(-3.6548858794907493, -1.6253643308191343, 0.25),
|
||||
float3(1.0130775986052671, -3.9967078676335834, 0.24253562503633297),
|
||||
float3(4.229723673607257, 0.33081361055181563, 0.23570226039551587),
|
||||
float3(0.40107790291173834, 4.340407413572593, 0.22941573387056174),
|
||||
float3(-4.319124570236028, 1.159811599693438, 0.22360679774997896),
|
||||
float3(-1.9209044802827355, -4.160543952132907, 0.2182178902359924),
|
||||
float3(3.8639122286635708, -2.6589814382925123, 0.21320071635561041),
|
||||
float3(3.3486228404946234, 3.4331800232609, 0.20851441405707477),
|
||||
float3(-2.8769733643574344, 3.9652268864187157, 0.20412414523193154)
|
||||
};
|
||||
|
||||
// minimum luminance for a pixel to contribute bloom
|
||||
static const float BLOOM_THRESHOLD = 0.2f;
|
||||
// strength of the bloom contribution
|
||||
static const float BLOOM_STRENGTH = 0.2f;
|
||||
|
||||
float
|
||||
lum(float4 c) {
|
||||
return 0.299f * c.r + 0.587f * c.g + 0.114f * c.b;
|
||||
}
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
float2 uv = t.pos;
|
||||
|
||||
// One pixel in backbuffer UV space; scale by sqrt(2) to match original step
|
||||
float2 step = float2(1.414f) / float2(d.viewport_size_pixels);
|
||||
|
||||
float4 result = color;
|
||||
|
||||
[ForceUnroll]
|
||||
for (int i = 0; i < 24; i++) {
|
||||
float3 s = samples[i];
|
||||
float4 sc = t.backbuffer.Sample(uv + s.xy * step);
|
||||
float l = lum(sc);
|
||||
result += (float4)(l * s.z * sc * BLOOM_STRENGTH) * ::step(BLOOM_THRESHOLD, l);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
var float4 TINT = float4(0, 0.8, 0.6, 1)
|
||||
|
||||
startgroup
|
||||
shaders crt
|
||||
endgroup
|
||||
@@ -0,0 +1,55 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Original shader: https://www.shadertoy.com/view/WsVSzV (CC BY NC SA 3.0)
|
||||
// Ported to slang and modified for kitty
|
||||
//
|
||||
// Note that this shader does not work with background_opacity < 1
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
static const float WARP = 0.25f; // simulates curvature of CRT monitor
|
||||
static const float SCAN = 0.50f; // simulates darkness between scanlines
|
||||
static const float4 TINT = float4(0, 0.8, 0.6, 0); // tint color set the fourth component to 1 to apply it fully
|
||||
|
||||
// Warp UV to simulate CRT screen curvature
|
||||
float2
|
||||
warp(float2 uv) {
|
||||
// Squared distance from center (drives curvature)
|
||||
float2 dc = abs(0.5f - uv);
|
||||
dc *= dc;
|
||||
uv.x -= 0.5f;
|
||||
uv.x *= 1.0f + (dc.y * (0.3f * WARP));
|
||||
uv.x += 0.5f;
|
||||
uv.y -= 0.5f;
|
||||
uv.y *= 1.0f + (dc.x * (0.4f * WARP));
|
||||
uv.y += 0.5f;
|
||||
return uv;
|
||||
}
|
||||
|
||||
// Make clicks land on the text that is shown under the pointer
|
||||
public float2
|
||||
pointer_map(float2 pos, KittyCustomShaderData d) {
|
||||
return warp(pos);
|
||||
}
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
// UV within the current viewport (0..1)
|
||||
float2 uv = warp(t.pos);
|
||||
|
||||
// Original Y pixel coordinate within the viewport (for scanline phase)
|
||||
float fragCoordY = t.pos.y * float(d.viewport_size_pixels.y) * t.viewport.w;
|
||||
|
||||
// Scanline darkness at this pixel row
|
||||
float apply = abs(sin(fragCoordY) * 0.25f * SCAN);
|
||||
|
||||
// Sample the backbuffer at the warped viewport UV
|
||||
float3 col = t.backbuffer.Sample(uv).rgb;
|
||||
// apply the tint
|
||||
col = lerp(col, col * TINT.rgb, TINT.a);
|
||||
|
||||
// since this shaders moves pixels around it cannot work with alpha < 1
|
||||
return float4(lerp(col, float3(0.0f), apply), 1);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
startgroup
|
||||
animation_start cursor-trail-move
|
||||
animation_stop cursor-trail-stop
|
||||
shaders cursor-trail-blaze
|
||||
endgroup
|
||||
@@ -0,0 +1,135 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Blaze cursor trail — port of https://gist.github.com/chardskarth/95874c54e29da6b5a36ab7b50ae2d088
|
||||
// by chardskarth. Draws a fading parallelogram trail from the previous cursor
|
||||
// position to the current one, coloured with an amber fill and red-orange border.
|
||||
// Ported to slang for kitty
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
static const float4 TRAIL_COLOR = float4(1.0, 0.725, 0.161, 1.0);
|
||||
static const float4 TRAIL_COLOR_ACCENT = float4(1.0, 0.0, 0.0, 1.0);
|
||||
// Trail lifetime in seconds.
|
||||
static const float DURATION = 0.5;
|
||||
|
||||
// pow(1 - x, 10) via repeated squaring — branchless ease-out.
|
||||
static float
|
||||
ease_out10(float x) {
|
||||
float y = 1.0 - x;
|
||||
float y2 = y * y;
|
||||
float y4 = y2 * y2;
|
||||
return y4 * y4 * y2;
|
||||
}
|
||||
|
||||
// Smooth blend curve for the progress value.
|
||||
static float
|
||||
blend_smooth(float t) {
|
||||
float s = t * t;
|
||||
return s / (2.0 * (s - t) + 1.0);
|
||||
}
|
||||
|
||||
// SDF of an axis-aligned box. p = query point, center = box centre, hext = half-extents.
|
||||
static float
|
||||
sdBox(float2 p, float2 center, float2 hext) {
|
||||
float2 d = abs(p - center) - hext;
|
||||
return length(max(d, float2(0.0))) + min(max(d.x, d.y), 0.0);
|
||||
}
|
||||
|
||||
// Single edge contribution for the quadrilateral SDF (signed winding accumulation).
|
||||
static float
|
||||
seg(float2 p, float2 a, float2 b, inout float s, float d) {
|
||||
float2 e = b - a;
|
||||
float2 w = p - a;
|
||||
float2 proj = a + e * clamp(dot(w, e) / dot(e, e), 0.0, 1.0);
|
||||
d = min(d, dot(p - proj, p - proj));
|
||||
|
||||
float c0 = step(0.0, p.y - a.y);
|
||||
float c1 = 1.0 - step(0.0, p.y - b.y);
|
||||
float c2 = 1.0 - step(0.0, e.x * w.y - e.y * w.x);
|
||||
float allCond = c0 * c1 * c2;
|
||||
float noneCond = (1.0 - c0) * (1.0 - c1) * (1.0 - c2);
|
||||
s *= lerp(1.0, -1.0, step(0.5, allCond + noneCond));
|
||||
return d;
|
||||
}
|
||||
|
||||
// SDF of an arbitrary quadrilateral (uses winding number via four edge contributions).
|
||||
static float
|
||||
sdQuad(float2 p, float2 v0, float2 v1, float2 v2, float2 v3) {
|
||||
float s = 1.0;
|
||||
float d = dot(p - v0, p - v0);
|
||||
d = seg(p, v0, v3, s, d);
|
||||
d = seg(p, v1, v0, s, d);
|
||||
d = seg(p, v2, v1, s, d);
|
||||
d = seg(p, v3, v2, s, d);
|
||||
return s * sqrt(d);
|
||||
}
|
||||
|
||||
// Returns 0 for diagonal movement (up-left / down-right), 1 otherwise.
|
||||
// Selects which corner of the parallelogram aligns with the movement direction.
|
||||
static float
|
||||
movementVertexFactor(float2 a, float2 b) {
|
||||
float c1 = step(b.x, a.x) * step(a.y, b.y);
|
||||
float c2 = step(a.x, b.x) * step(b.y, a.y);
|
||||
return 1.0 - max(c1, c2);
|
||||
}
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
if (d.cursor_trail_color.a <= 0.0) return color;
|
||||
|
||||
if (d.cursor_trail_age < 0.0) return color;
|
||||
float age = clamp(d.cursor_trail_age / DURATION, 0.0, 1.0);
|
||||
if (age >= 1.0) return color;
|
||||
|
||||
float easedProgress = ease_out10(blend_smooth(age));
|
||||
if (easedProgress <= 0.0) return color;
|
||||
|
||||
// Work in pixel space for correct aspect-ratio distance measurements.
|
||||
float2 pixelDims = float2(d.viewport_size_pixels) * t.viewport.zw;
|
||||
float2 px = t.pos * pixelDims;
|
||||
|
||||
// Current cursor rect in pixel space (edge: .x=left .y=right .z=top .w=bottom, y-up).
|
||||
float curLeft = d.cursor_trail_edge.x * pixelDims.x;
|
||||
float curRight = d.cursor_trail_edge.y * pixelDims.x;
|
||||
float curTop = d.cursor_trail_edge.z * pixelDims.y;
|
||||
float curBottom = d.cursor_trail_edge.w * pixelDims.y;
|
||||
float curWidth = curRight - curLeft;
|
||||
float curHeight = curTop - curBottom;
|
||||
float2 curCenter = float2((curLeft + curRight) * 0.5, (curTop + curBottom) * 0.5);
|
||||
|
||||
float prevLeft = d.cursor_trail_prev_edge.x * pixelDims.x;
|
||||
float prevTop = d.cursor_trail_prev_edge.z * pixelDims.y;
|
||||
float prevBottom = d.cursor_trail_prev_edge.w * pixelDims.y;
|
||||
float2 prevCenter = float2(
|
||||
(d.cursor_trail_prev_edge.x + d.cursor_trail_prev_edge.y) * 0.5 * pixelDims.x,
|
||||
(d.cursor_trail_prev_edge.z + d.cursor_trail_prev_edge.w) * 0.5 * pixelDims.y);
|
||||
|
||||
float lineLength = length(curCenter - prevCenter);
|
||||
// Alpha fades to 0 at the previous-cursor end, reaching full effect at the current cursor.
|
||||
float alphaModifier = min(length(px - curCenter) / (lineLength * easedProgress), 1.0);
|
||||
|
||||
// Build parallelogram vertices in pixel space.
|
||||
float vf = movementVertexFactor(curCenter, prevCenter);
|
||||
float ivf = 1.0 - vf;
|
||||
float2 v0 = float2(lerp(curLeft, curRight, vf), curBottom);
|
||||
float2 v1 = float2(lerp(curLeft, curRight, ivf), curTop);
|
||||
float2 v2 = float2(prevLeft + curWidth * ivf, prevTop);
|
||||
float2 v3 = float2(prevLeft + curWidth * vf, prevBottom);
|
||||
|
||||
float sdfCursor = sdBox(px, curCenter, float2(curWidth, curHeight) * 0.5);
|
||||
float sdfTrail = sdQuad(px, v0, v1, v2, v3);
|
||||
|
||||
// ~2-pixel anti-aliasing range in pixel space.
|
||||
float aaRange = 2.0;
|
||||
float4 newColor = color;
|
||||
// Inner border accent (red-orange inside the trail edges).
|
||||
newColor = lerp(newColor, TRAIL_COLOR_ACCENT, 1.0 - smoothstep(sdfTrail, -aaRange, aaRange * 0.05));
|
||||
// Main amber fill.
|
||||
newColor = lerp(newColor, TRAIL_COLOR, 1.0 - smoothstep(0.0, aaRange, sdfTrail));
|
||||
// Fade: effect is weakest toward the previous cursor end.
|
||||
newColor = lerp(color, newColor, 1.0 - alphaModifier);
|
||||
// Restore original pixels inside the cursor rectangle.
|
||||
return lerp(newColor, color, step(sdfCursor, 0.0));
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
startgroup
|
||||
animation_start cursor-trail-move
|
||||
animation_stop cursor-trail-stop
|
||||
shaders cursor-trail-default
|
||||
endgroup
|
||||
@@ -0,0 +1,58 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Custom cursor trail shader — replicates the built-in trail using the
|
||||
// cursor_trail_* uniforms. Use as a starting point for custom effects.
|
||||
//
|
||||
// Suggested pipeline config:
|
||||
// startgroup
|
||||
// animation_start cursor-trail-move
|
||||
// animation_stop cursor-trail-stop
|
||||
// shaders cursor-trail
|
||||
// endgroup
|
||||
//
|
||||
// Note: animation_progress is not tied to the trail duration (which is
|
||||
// an exponential decay of variable length). Use cursor_trail_color.a
|
||||
// for opacity and the corner positions for geometry instead.
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
// Returns true when uv is inside the convex quad c0→c1→c2→c3 (clockwise, y-up).
|
||||
// Corner order from cursor_trail_corners_*: 0=top-right, 1=bottom-right, 2=bottom-left, 3=top-left.
|
||||
bool
|
||||
inside_trail_quad(float2 uv, float2 c0, float2 c1, float2 c2, float2 c3) {
|
||||
float2 e0 = c1 - c0;
|
||||
float2 e1 = c2 - c1;
|
||||
float2 e2 = c3 - c2;
|
||||
float2 e3 = c0 - c3;
|
||||
float s0 = e0.x * (uv.y - c0.y) - e0.y * (uv.x - c0.x);
|
||||
float s1 = e1.x * (uv.y - c1.y) - e1.y * (uv.x - c1.x);
|
||||
float s2 = e2.x * (uv.y - c2.y) - e2.y * (uv.x - c2.x);
|
||||
float s3 = e3.x * (uv.y - c3.y) - e3.y * (uv.x - c3.x);
|
||||
return s0 <= 0.0 && s1 <= 0.0 && s2 <= 0.0 && s3 <= 0.0;
|
||||
}
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
float opacity = d.cursor_trail_color.a;
|
||||
if (opacity <= 0.0) return color;
|
||||
|
||||
float2 uv = t.pos;
|
||||
|
||||
float2 c0 = float2(d.cursor_trail_corners_x.x, d.cursor_trail_corners_y.x); // top-right
|
||||
float2 c1 = float2(d.cursor_trail_corners_x.y, d.cursor_trail_corners_y.y); // bottom-right
|
||||
float2 c2 = float2(d.cursor_trail_corners_x.z, d.cursor_trail_corners_y.z); // bottom-left
|
||||
float2 c3 = float2(d.cursor_trail_corners_x.w, d.cursor_trail_corners_y.w); // top-left
|
||||
|
||||
if (!inside_trail_quad(uv, c0, c1, c2, c3)) return color;
|
||||
|
||||
// Mask out the cursor's current rectangle so the real cursor renders cleanly on top.
|
||||
// cursor_trail_edge: .x=left, .y=right, .z=top, .w=bottom (UV, y-up)
|
||||
float inside_cursor =
|
||||
step(d.cursor_trail_edge.x, uv.x) * step(uv.x, d.cursor_trail_edge.y) * step(d.cursor_trail_edge.w, uv.y) * step(uv.y, d.cursor_trail_edge.z);
|
||||
opacity *= 1.0 - inside_cursor;
|
||||
if (opacity <= 0.0) return color;
|
||||
|
||||
return float4(lerp(color.rgb, d.cursor_trail_color.rgb, opacity), color.a);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
startgroup
|
||||
animation_start cursor-trail-move
|
||||
animation_stop cursor-trail-stop
|
||||
shaders cursor-trail-lightning
|
||||
endgroup
|
||||
@@ -0,0 +1,138 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Lightning cursor trail — port of cursor_lightning.glsl to slang for kitty
|
||||
// Draws a brief jagged bolt from the previous cursor position to the current one.
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
static const float3 BOLT_COLOR = float3(1.00, 0.82, 0.72);
|
||||
static const float3 GLOW_COLOR = float3(0.74, 0.00, 0.00);
|
||||
// Bolt lifetime in seconds.
|
||||
static const float DURATION = 0.14;
|
||||
// Sideways displacement relative to bolt length.
|
||||
static const float JAGGEDNESS = 0.085;
|
||||
// Core stroke width in pixels.
|
||||
static const float CORE_WIDTH = 1.15;
|
||||
// Glow radius in pixels.
|
||||
static const float GLOW_WIDTH = 5.5;
|
||||
// Number of linear segments that make up the main bolt.
|
||||
static const int BOLT_SEGMENTS = 12;
|
||||
|
||||
static float
|
||||
hash11(float p) {
|
||||
p = frac(p * 0.1031);
|
||||
p *= p + 33.33;
|
||||
p *= p + p;
|
||||
return frac(p);
|
||||
}
|
||||
|
||||
static float
|
||||
segDist(float2 p, float2 a, float2 b) {
|
||||
float2 ab = b - a;
|
||||
float t = clamp(dot(p - a, ab) / max(dot(ab, ab), 1e-7), 0.0, 1.0);
|
||||
return length(p - (a + ab * t));
|
||||
}
|
||||
|
||||
// A point on the piecewise-linear bolt. Endpoints stay fixed; interior nodes
|
||||
// are displaced perpendicular to the travel direction.
|
||||
static float2
|
||||
boltPoint(float2 a, float2 b, float t, float seed) {
|
||||
float2 delta = b - a;
|
||||
float boltLength = length(delta);
|
||||
float2 perp = float2(-delta.y, delta.x) / max(boltLength, 1e-5);
|
||||
float node = floor(t * float(BOLT_SEGMENTS) + 0.5);
|
||||
float rnd = hash11(node * 17.17 + seed) * 2.0 - 1.0;
|
||||
float fade = sin(3.14159265 * t);
|
||||
return lerp(a, b, t) + perp * rnd * boltLength * JAGGEDNESS * fade;
|
||||
}
|
||||
|
||||
// Minimum distance from p to the main bolt's piecewise-linear path.
|
||||
static float
|
||||
mainBoltDist(float2 p, float2 a, float2 b, float seed) {
|
||||
float minD = 1e5;
|
||||
float2 prev = a;
|
||||
[ForceUnroll]
|
||||
for (int i = 1; i <= BOLT_SEGMENTS; i++) {
|
||||
float t = float(i) / float(BOLT_SEGMENTS);
|
||||
float2 cur = boltPoint(a, b, t, seed);
|
||||
minD = min(minD, segDist(p, prev, cur));
|
||||
prev = cur;
|
||||
}
|
||||
return minD;
|
||||
}
|
||||
|
||||
// Three small forks growing out of alternating points on the main bolt.
|
||||
static float
|
||||
forkDist(float2 p, float2 a, float2 b, float seed) {
|
||||
float minD = 1e5;
|
||||
float2 delta = b - a;
|
||||
float boltLength = length(delta);
|
||||
float2 perp = float2(-delta.y, delta.x) / max(boltLength, 1e-5);
|
||||
float2 dir = normalize(delta);
|
||||
|
||||
[ForceUnroll]
|
||||
for (int i = 0; i < 3; i++) {
|
||||
float fi = float(i);
|
||||
float t = 0.28 + fi * 0.22;
|
||||
float2 root = boltPoint(a, b, t, seed);
|
||||
float side = lerp(-1.0, 1.0, step(0.5, hash11(seed + fi * 41.0)));
|
||||
float reach = boltLength * (0.055 + 0.035 * hash11(seed + fi * 53.0));
|
||||
float2 along = dir * reach * (hash11(seed + fi * 67.0) - 0.35);
|
||||
float2 tip = root + perp * side * reach + along;
|
||||
float2 elbow = lerp(root, tip, 0.52) - perp * side * reach * (0.12 + 0.18 * hash11(seed + fi * 79.0));
|
||||
minD = min(minD, segDist(p, root, elbow));
|
||||
minD = min(minD, segDist(p, elbow, tip));
|
||||
}
|
||||
return minD;
|
||||
}
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
if (d.cursor_trail_age < 0.0) return color;
|
||||
float age = clamp(d.cursor_trail_age / DURATION, 0.0, 1.0);
|
||||
if (age >= 1.0) return color;
|
||||
|
||||
float2 pixelDims = float2(d.viewport_size_pixels) * t.viewport.zw;
|
||||
|
||||
// Cursor centres in pixel space (edge: .x=left .y=right .z=top .w=bottom, y-up).
|
||||
float2 curCenter = float2((d.cursor_trail_edge.x + d.cursor_trail_edge.y) * 0.5, (d.cursor_trail_edge.z + d.cursor_trail_edge.w) * 0.5) * pixelDims;
|
||||
float2 prevCenter =
|
||||
float2((d.cursor_trail_prev_edge.x + d.cursor_trail_prev_edge.y) * 0.5, (d.cursor_trail_prev_edge.z + d.cursor_trail_prev_edge.w) * 0.5) * pixelDims;
|
||||
|
||||
float cursorWidth = (d.cursor_trail_edge.y - d.cursor_trail_edge.x) * pixelDims.x;
|
||||
|
||||
float2 px = t.pos * pixelDims;
|
||||
|
||||
// Derive the seed from the cursor positions for a stable bolt shape across
|
||||
// the bolt's lifetime, the event time is too imprecise once kitty has been
|
||||
// running for a while.
|
||||
float seed = dot(floor(prevCenter), float2(0.013, 0.0171)) + dot(floor(curCenter), float2(0.0037, 0.029));
|
||||
|
||||
float mainD = mainBoltDist(px, prevCenter, curCenter, seed);
|
||||
float forkD = forkDist(px, prevCenter, curCenter, seed);
|
||||
|
||||
float pixel = max(fwidth(mainD), 0.65);
|
||||
float core = 1.0 - smoothstep(CORE_WIDTH, CORE_WIDTH + pixel, mainD);
|
||||
float forkCore = 1.0 - smoothstep(CORE_WIDTH * 0.72, CORE_WIDTH * 0.72 + pixel, forkD);
|
||||
float glow = exp(-mainD * mainD / (GLOW_WIDTH * GLOW_WIDTH));
|
||||
float forkGlow = exp(-forkD * forkD / (GLOW_WIDTH * GLOW_WIDTH * 0.55));
|
||||
|
||||
// Flash hard, then rapidly lose the core, leaving only glow.
|
||||
float flash = 1.0 - smoothstep(0.0, 1.0, age);
|
||||
flash *= flash;
|
||||
float flicker = 0.82 + 0.18 * sin(age * 95.0 + seed);
|
||||
float glowAmt = max(glow, forkGlow * 0.55) * flash * flicker * 0.72;
|
||||
float coreAmt = max(core, forkCore * 0.82) * flash * flicker;
|
||||
|
||||
float3 rgb = lerp(color.rgb, GLOW_COLOR, clamp(glowAmt, 0.0, 1.0));
|
||||
rgb = lerp(rgb, BOLT_COLOR, clamp(coreAmt, 0.0, 1.0));
|
||||
|
||||
// Keep the cursor crisp above the effect.
|
||||
float insideCursor = step(d.cursor_trail_edge.x, t.pos.x) * step(t.pos.x, d.cursor_trail_edge.y) * step(d.cursor_trail_edge.w, t.pos.y) *
|
||||
step(t.pos.y, d.cursor_trail_edge.z);
|
||||
rgb = lerp(rgb, color.rgb, insideCursor);
|
||||
|
||||
return float4(rgb, color.a);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
startgroup
|
||||
animation_start cursor-trail-move
|
||||
animation_stop cursor-trail-stop
|
||||
shaders cursor-trail-motion-blur
|
||||
endgroup
|
||||
@@ -0,0 +1,148 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// A smoother cursor trail, using motion blur.
|
||||
//
|
||||
// When the cursor jumps to a new place, kitty draws a trail that stretches
|
||||
// from where the cursor was towards where it is now, and then quickly shrinks
|
||||
// into the cursor. The screen is redrawn many times a second and each redraw
|
||||
// shows the trail in a new position. When the cursor moves fast, those
|
||||
// positions are far apart, so the trail can look like it is hopping from place
|
||||
// to place instead of gliding.
|
||||
//
|
||||
// This shader smooths that out the same way a camera does. A photo of
|
||||
// something moving fast comes out streaked, because the object kept moving
|
||||
// while the shutter was open. Similarly, every time the screen is redrawn,
|
||||
// this shader draws the trail at many in-between positions, from where it was
|
||||
// in the previous redraw to where it is now, and blends them together. The
|
||||
// result is a soft streak that looks like continuous motion. It also smooths
|
||||
// the slanted edges of the trail, so they look clean rather than jagged
|
||||
// (antialiasing).
|
||||
//
|
||||
// To use it, add the following to kitty.conf:
|
||||
// cursor_trail 1
|
||||
// custom_shaders cursor-trail-motion-blur
|
||||
//
|
||||
// You can tune the options below without editing this file. Save a pipeline
|
||||
// file such as shaders/my-trail.pipeline in your kitty config directory,
|
||||
// containing, for example:
|
||||
// startgroup
|
||||
// animation_start cursor-trail-move
|
||||
// animation_stop cursor-trail-stop
|
||||
// var bool CONNECTED true
|
||||
// var int MOTION_BLUR_SAMPLES 32
|
||||
// shaders cursor-trail-motion-blur
|
||||
// endgroup
|
||||
// and then use custom_shaders my-trail in kitty.conf.
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
// Turn motion blur on or off. When off, only antialiasing is applied.
|
||||
static const bool MOTION_BLUR = true;
|
||||
// Number of in-between positions blended per redraw. More is smoother but
|
||||
// slower. Values are limited to the range 1..64.
|
||||
static const int MOTION_BLUR_SAMPLES = 16;
|
||||
// Smooth the edges of the trail.
|
||||
static const bool ANTIALIASING = true;
|
||||
// When true, the blur reaches all the way into the cursor, so the trail looks
|
||||
// like one continuous streak. When false, the trail keeps kitty's usual look,
|
||||
// where its tail lags slightly behind the cursor.
|
||||
static const bool CONNECTED = false;
|
||||
|
||||
// All positions below are in pixels.
|
||||
|
||||
// How much of the pixel centered at p lies outside the edge a→b, from 0 (none
|
||||
// of it) to 1 (all of it). orientation is +1 for triangles whose corners are
|
||||
// in counter-clockwise order and -1 for clockwise.
|
||||
static float
|
||||
outside_edge(float2 p, float2 a, float2 b, float orientation) {
|
||||
float2 e = b - a;
|
||||
// Signed distance from the edge, positive on the inner side
|
||||
float dist = orientation * (e.x * (p.y - a.y) - e.y * (p.x - a.x)) / length(e);
|
||||
if (!ANTIALIASING) return dist < 0.0 ? 1.0 : 0.0;
|
||||
return 1.0 - saturate(0.5 + dist);
|
||||
}
|
||||
|
||||
// The fraction of the pixel centered at p that is covered by the triangle abc.
|
||||
// Subtracting the part of the pixel outside each edge is exact for straight
|
||||
// edges and also stays correct for slivers thinner than a pixel.
|
||||
static float
|
||||
triangle_coverage(float2 p, float2 a, float2 b, float2 c) {
|
||||
float area = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
|
||||
// A triangle that has collapsed to a line or point covers nothing
|
||||
if (abs(area) < 1e-6) return 0.0;
|
||||
float orientation = area > 0.0 ? 1.0 : -1.0;
|
||||
return saturate(1.0 - outside_edge(p, a, b, orientation) - outside_edge(p, b, c, orientation) - outside_edge(p, c, a, orientation));
|
||||
}
|
||||
|
||||
// The fraction of the pixel centered at p covered by the trail. Corner order
|
||||
// is top-right, bottom-right, bottom-left, top-left. The quad is split into
|
||||
// the same two triangles as kitty's built-in trail renderer.
|
||||
static float
|
||||
trail_coverage(float2 p, float4 xs, float4 ys) {
|
||||
float2 c0 = float2(xs.x, ys.x);
|
||||
float2 c1 = float2(xs.y, ys.y);
|
||||
float2 c2 = float2(xs.z, ys.z);
|
||||
float2 c3 = float2(xs.w, ys.w);
|
||||
return min(triangle_coverage(p, c0, c1, c2) + triangle_coverage(p, c0, c2, c3), 1.0);
|
||||
}
|
||||
|
||||
// The fraction of the pixel centered at p covered by the axis aligned
|
||||
// rectangle from lo to hi.
|
||||
static float
|
||||
rect_coverage(float2 p, float2 lo, float2 hi) {
|
||||
if (!ANTIALIASING) return (p.x >= lo.x && p.x <= hi.x && p.y >= lo.y && p.y <= hi.y) ? 1.0 : 0.0;
|
||||
float2 overlap = saturate(min(p + 0.5, hi) - max(p - 0.5, lo));
|
||||
return overlap.x * overlap.y;
|
||||
}
|
||||
|
||||
static float
|
||||
min4(float4 v) {
|
||||
return min(min(v.x, v.y), min(v.z, v.w));
|
||||
}
|
||||
|
||||
static float
|
||||
max4(float4 v) {
|
||||
return max(max(v.x, v.y), max(v.z, v.w));
|
||||
}
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
float opacity = d.cursor_trail_color.a;
|
||||
if (opacity <= 0.0 || d.cursor_trail_state <= 0.0) return color;
|
||||
|
||||
float2 pixel_dims = max(float2(d.viewport_size_pixels) * t.viewport.zw, float2(1.0));
|
||||
float2 p = t.pos * pixel_dims;
|
||||
// cursor_trail_edge: .x=left, .y=right, .z=top, .w=bottom
|
||||
float2 cursor_lo = float2(d.cursor_trail_edge.x, d.cursor_trail_edge.w) * pixel_dims;
|
||||
float2 cursor_hi = float2(d.cursor_trail_edge.y, d.cursor_trail_edge.z) * pixel_dims;
|
||||
|
||||
float4 end_x = d.cursor_trail_corners_x * pixel_dims.x;
|
||||
float4 end_y = d.cursor_trail_corners_y * pixel_dims.y;
|
||||
if (MOTION_BLUR && CONNECTED) {
|
||||
end_x = float4(cursor_hi.x, cursor_hi.x, cursor_lo.x, cursor_lo.x);
|
||||
end_y = float4(cursor_hi.y, cursor_lo.y, cursor_lo.y, cursor_hi.y);
|
||||
}
|
||||
float4 start_x = MOTION_BLUR ? d.cursor_trail_prev_corners_x * pixel_dims.x : end_x;
|
||||
float4 start_y = MOTION_BLUR ? d.cursor_trail_prev_corners_y * pixel_dims.y : end_y;
|
||||
|
||||
// This runs for every pixel on screen, so skip pixels that are outside
|
||||
// the area swept by the trail in this redraw.
|
||||
float2 swept_lo = float2(min(min4(start_x), min4(end_x)), min(min4(start_y), min4(end_y))) - 1.0;
|
||||
float2 swept_hi = float2(max(max4(start_x), max4(end_x)), max(max4(start_y), max4(end_y))) + 1.0;
|
||||
if (p.x < swept_lo.x || p.x > swept_hi.x || p.y < swept_lo.y || p.y > swept_hi.y) return color;
|
||||
|
||||
const int samples = MOTION_BLUR ? clamp(MOTION_BLUR_SAMPLES, 1, 64) : 1;
|
||||
float coverage = 0.0;
|
||||
for (int i = 0; i < samples; i++) {
|
||||
float time = MOTION_BLUR ? (float(i) + 0.5) / float(samples) : 1.0;
|
||||
coverage += trail_coverage(p, lerp(start_x, end_x, time), lerp(start_y, end_y, time));
|
||||
}
|
||||
coverage /= float(samples);
|
||||
// Never paint over the cursor itself, so that it renders cleanly on top.
|
||||
coverage *= 1.0 - rect_coverage(p, cursor_lo, cursor_hi);
|
||||
if (coverage <= 0.0) return color;
|
||||
|
||||
return float4(lerp(color.rgb, d.cursor_trail_color.rgb, saturate(opacity * coverage)), color.a);
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Particles that fly off the cursor as it moves, in the style of the cursor
|
||||
// effects in neovide. There are three styles, selected with MODE below:
|
||||
//
|
||||
// railgun - particles are fired sideways from the path of the cursor, in
|
||||
// a slowly turning direction, so they form a spiral.
|
||||
// torpedo - particles are blown backwards from the path of the cursor,
|
||||
// like the wake of a torpedo.
|
||||
// pixiedust - glittering particles drift gently downwards from the path
|
||||
// of the cursor.
|
||||
//
|
||||
// Every style has a ready made pipeline, so to use it, add the following to
|
||||
// kitty.conf:
|
||||
// cursor_trail 1
|
||||
// custom_shaders cursor-trail-railgun
|
||||
// or cursor-trail-torpedo or cursor-trail-pixiedust.
|
||||
//
|
||||
// You can tune the options below without editing this file. Save a pipeline
|
||||
// file such as shaders/my-particles.pipeline in your kitty config directory,
|
||||
// containing, for example:
|
||||
// startgroup
|
||||
// animation_start cursor-trail-move
|
||||
// animation_stop 1300
|
||||
// animation_step 16
|
||||
// var int MODE 2
|
||||
// var float LIFETIME 1.1
|
||||
// var float4 PARTICLE_COLOR float4(1, 0.8, 0.2, 1)
|
||||
// shaders cursor-trail-default cursor-trail-particles
|
||||
// endgroup
|
||||
// and then use custom_shaders my-particles in kitty.conf. Particles are drawn
|
||||
// for a few recent cursor moves at a time, so they keep flying while you move
|
||||
// the cursor again. The number in animation_stop is how many milliseconds
|
||||
// after the last cursor move to keep drawing, it must be more than
|
||||
// LIFETIME + EMIT_DURATION, otherwise particles will vanish early. Leave out
|
||||
// cursor-trail-default to get only the particles without kitty's usual trail.
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
static const int RAILGUN = 0;
|
||||
static const int TORPEDO = 1;
|
||||
static const int PIXIEDUST = 2;
|
||||
|
||||
// Which style to use, 0 for railgun, 1 for torpedo and 2 for pixiedust.
|
||||
static const int MODE = RAILGUN;
|
||||
// The color of the particles. When the alpha is zero, the color of the cursor
|
||||
// trail is used, see the cursor_trail_color option in kitty.conf.
|
||||
static const float4 PARTICLE_COLOR = float4(0.0);
|
||||
// How opaque the particles are, from 0 to 1.
|
||||
static const float OPACITY = 1.0;
|
||||
// Maximum number of particles for every cursor move. More looks richer but is
|
||||
// slower. Values are limited to the range 1..64.
|
||||
static const int MAX_PARTICLES = 48;
|
||||
// How many particles to emit for every line height of distance the cursor
|
||||
// moves, so short moves produce fewer particles than long jumps. At least a few particles are always
|
||||
// emitted.
|
||||
static const float PARTICLE_DENSITY = 3.0;
|
||||
// How long particles live, in seconds. Individual particles live a little
|
||||
// shorter, at random, so they do not all vanish at the same time.
|
||||
static const float LIFETIME = 0.8;
|
||||
// Particles are not emitted all at once, but in sequence as the cursor
|
||||
// travels from its old position to its new one, taking this many seconds.
|
||||
static const float EMIT_DURATION = 0.08;
|
||||
// The radius of the particles, as a fraction of the size of the cursor.
|
||||
static const float PARTICLE_SIZE = 0.12;
|
||||
// The speed at which particles are launched, in cursor sizes per second.
|
||||
static const float SPEED = 20.0;
|
||||
// How fast particles slow down. Larger values make them stop sooner.
|
||||
static const float DRAG = 2.5;
|
||||
// How fast particles fall, in cursor sizes per second per second. Only used
|
||||
// by pixiedust, as the other styles are too fast to be affected by gravity.
|
||||
static const float GRAVITY = 8.0;
|
||||
// How quickly the launch direction turns in the railgun style, in radians
|
||||
// for every line height of distance the cursor moves.
|
||||
static const float RAILGUN_PHASE = 1.5;
|
||||
// How widely particles fan out in the torpedo style, in radians to either
|
||||
// side of directly backwards.
|
||||
static const float TORPEDO_SPREAD = 1.0;
|
||||
|
||||
static const float TAU = 6.28318530718;
|
||||
// Noise constant from Dave Hoskins
|
||||
static const float4 MOD4 = float4(0.1031, 0.1030, 0.0973, 0.1099);
|
||||
|
||||
static float4
|
||||
hash43(float3 p) {
|
||||
float4 p4 = frac(float4(p.xyzx) * MOD4);
|
||||
p4 += dot(p4, p4.wzxy + 33.33);
|
||||
return frac((p4.xxyz + p4.yzzw) * p4.zywx);
|
||||
}
|
||||
|
||||
static float2
|
||||
rotate(float2 v, float angle) {
|
||||
float c = cos(angle), s = sin(angle);
|
||||
return float2(c * v.x - s * v.y, s * v.x + c * v.y);
|
||||
}
|
||||
|
||||
// Distance travelled after time t by something launched at unit speed that
|
||||
// slows down due to DRAG.
|
||||
static float
|
||||
drag_distance(float t) {
|
||||
return DRAG > 0.0 ? (1.0 - exp(-DRAG * t)) / DRAG : t;
|
||||
}
|
||||
|
||||
// Seconds since move i, negative if there is no such move.
|
||||
static float
|
||||
move_age(KittyCustomShaderData d, int i) {
|
||||
return d.cursor_trail_history_age[i / 4][i % 4];
|
||||
}
|
||||
|
||||
// Center and size of a cursor rectangle given in UV edges, in pixels.
|
||||
static float4
|
||||
rect_center_and_size(float4 edges, float2 pixelDims) {
|
||||
float2 lb = float2(edges.x, edges.w) * pixelDims;
|
||||
float2 rt = float2(edges.y, edges.z) * pixelDims;
|
||||
return float4((lb + rt) * 0.5, abs(rt - lb));
|
||||
}
|
||||
|
||||
// The opacity of the particles from one cursor move at the pixel px.
|
||||
static float
|
||||
move_particles(float2 px, float2 from, float2 to, float scale, float lines, float age, float seed) {
|
||||
float2 path = to - from;
|
||||
float pathLen = length(path);
|
||||
float2 dir = pathLen > 0.0 ? path / pathLen : float2(1.0, 0.0);
|
||||
float2 perp = float2(-dir.y, dir.x);
|
||||
float speed = SPEED * scale;
|
||||
float radius = max(PARTICLE_SIZE * scale, 0.75);
|
||||
|
||||
int count = clamp(int(ceil(lines * PARTICLE_DENSITY)), min(4, MAX_PARTICLES), clamp(MAX_PARTICLES, 1, 64));
|
||||
float coverage = 0.0;
|
||||
for (int i = 0; i < count; i++) {
|
||||
float4 r = hash43(float3(float(i), seed, 17.0));
|
||||
float4 r2 = hash43(float3(seed, float(i), 59.0));
|
||||
// Where along the path the particle starts, 0 is the old cursor position
|
||||
float u = (float(i) + r.x) / float(count);
|
||||
float t = age - u * EMIT_DURATION;
|
||||
float life = LIFETIME * lerp(0.6, 1.0, r.y);
|
||||
if (t < 0.0 || t >= life) continue;
|
||||
|
||||
float2 start = lerp(from, to, u) + (r2.xy - 0.5) * scale * 0.5;
|
||||
float2 velocity;
|
||||
float2 fall = float2(0.0);
|
||||
float brightness = 1.0;
|
||||
if (MODE == TORPEDO) {
|
||||
velocity = rotate(-dir, (r.z * 2.0 - 1.0) * TORPEDO_SPREAD) * lerp(0.4, 1.0, r.w);
|
||||
} else if (MODE == PIXIEDUST) {
|
||||
velocity = rotate(float2(0.4, 0.0), r.z * TAU) * lerp(0.2, 1.0, r.w);
|
||||
fall = float2(0.0, -0.5 * GRAVITY * scale * t * t);
|
||||
// Glitter
|
||||
brightness = 0.55 + 0.45 * sin(t * 40.0 + r2.z * TAU);
|
||||
} else {
|
||||
velocity = rotate(perp, u * lines * RAILGUN_PHASE) * lerp(0.7, 1.0, r.w);
|
||||
}
|
||||
float2 pos = start + velocity * speed * drag_distance(t) + fall;
|
||||
float fade = 1.0 - t / life;
|
||||
// Particles shrink as they fade
|
||||
float rad = radius * lerp(0.5, 1.0, fade);
|
||||
// Antialiased disc
|
||||
float a = saturate(rad + 0.5 - length(px - pos)) * fade * brightness;
|
||||
coverage = max(coverage, a);
|
||||
}
|
||||
return coverage;
|
||||
}
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
float2 pixelDims = float2(d.viewport_size_pixels) * t.viewport.zw;
|
||||
float2 px = t.pos * pixelDims;
|
||||
// Upper bound on how far a particle can get from the path of its cursor move
|
||||
float reachPerScale = SPEED * drag_distance(LIFETIME) + 0.5 * (MODE == PIXIEDUST ? GRAVITY * LIFETIME * LIFETIME : 0.0) + PARTICLE_SIZE + 0.5;
|
||||
|
||||
float coverage = 0.0;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
float age = move_age(d, i);
|
||||
// Moves are most recent first, so all remaining ones are unused or older still
|
||||
if (age < 0.0 || age >= LIFETIME + EMIT_DURATION) break;
|
||||
float4 from = rect_center_and_size(d.cursor_trail_history_from[i], pixelDims);
|
||||
float4 to = rect_center_and_size(d.cursor_trail_history_to[i], pixelDims);
|
||||
// The width of a beam cursor and the height of an underline cursor
|
||||
// are tiny, so use the larger of the two dimensions for scale.
|
||||
float scale = max(max(to.z, to.w), 1.0);
|
||||
float reach = reachPerScale * scale + 1.0;
|
||||
if (any(px < min(from.xy, to.xy) - reach) || any(px > max(from.xy, to.xy) + reach)) continue;
|
||||
float lines = length(to.xy - from.xy) / scale;
|
||||
// The seed only needs to be stable over the lifetime of the move, so derive it from the end points of the move
|
||||
float seed = frac(dot(to.xy - from.xy, float2(0.1371, 0.2113)) + dot(to.xy, float2(0.0173, 0.0291))) * 1000.0;
|
||||
coverage = max(coverage, move_particles(px, from.xy, to.xy, scale, lines, age, seed));
|
||||
}
|
||||
coverage *= OPACITY;
|
||||
if (coverage <= 0.0) return color;
|
||||
float3 pcol = PARTICLE_COLOR.a > 0.0 ? PARTICLE_COLOR.rgb : d.cursor_trail_color.rgb;
|
||||
return float4(lerp(color.rgb, pcol, saturate(coverage)), color.a);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
startgroup
|
||||
animation_start cursor-trail-move
|
||||
animation_stop 1000
|
||||
animation_step 16
|
||||
var int MODE 2
|
||||
shaders cursor-trail-default cursor-trail-particles
|
||||
endgroup
|
||||
@@ -0,0 +1,7 @@
|
||||
startgroup
|
||||
animation_start cursor-trail-move
|
||||
animation_stop 1000
|
||||
animation_step 16
|
||||
var int MODE 0
|
||||
shaders cursor-trail-default cursor-trail-particles
|
||||
endgroup
|
||||
@@ -0,0 +1,7 @@
|
||||
startgroup
|
||||
animation_start cursor-trail-move
|
||||
animation_stop 1000
|
||||
animation_step 16
|
||||
var int MODE 1
|
||||
shaders cursor-trail-default cursor-trail-particles
|
||||
endgroup
|
||||
Executable
+404
@@ -0,0 +1,404 @@
|
||||
#!./kitty/launcher/kitty +launch
|
||||
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import glob
|
||||
import math
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from threading import Thread
|
||||
from typing import Any
|
||||
|
||||
from kitty.constants import glfw_path
|
||||
from kitty.fast_data_types import GLFW_FKEY_ESCAPE as KEY_ESCAPE
|
||||
from kitty.fast_data_types import GLFW_MOUSE_BUTTON_LEFT as MOUSE_BUTTON_LEFT
|
||||
from kitty.fast_data_types import GLFW_PRESS as PRESS
|
||||
from kitty.fast_data_types import GLFW_RELEASE as RELEASE
|
||||
from kitty.fast_data_types import (
|
||||
glfw_wayland_inject_init,
|
||||
glfw_wayland_inject_key,
|
||||
glfw_wayland_inject_mouse_button,
|
||||
glfw_wayland_inject_mouse_motion_absolute,
|
||||
glfw_wayland_inject_terminate,
|
||||
)
|
||||
|
||||
DEFAULT_DURATION = 3
|
||||
DEFAULT_INITIAL_SLEEP = 3
|
||||
SCREEN_WIDTH = 600
|
||||
SCREEN_HEIGHT = 400
|
||||
|
||||
SWAY_CONFIG = f"""\
|
||||
output HEADLESS-1 resolution {SCREEN_WIDTH}x{SCREEN_HEIGHT} scale 1
|
||||
default_border none
|
||||
default_floating_border none
|
||||
hide_edge_borders both
|
||||
gaps inner 0
|
||||
gaps outer 0
|
||||
bar {{
|
||||
mode invisible
|
||||
}}
|
||||
"""
|
||||
|
||||
# Module-level state, set by do_one() before calling animate functions
|
||||
_sway_socket: str = ''
|
||||
_wayland_display: str = ''
|
||||
_kitty_socket: str = ''
|
||||
|
||||
|
||||
def get_runtime_dir() -> str:
|
||||
return os.environ.get('XDG_RUNTIME_DIR', f'/run/user/{os.getuid()}')
|
||||
|
||||
|
||||
def move_mouse(geometry: tuple[int, int, int, int], x: int, y: int) -> None:
|
||||
abs_x = geometry[0] + x
|
||||
abs_y = geometry[1] + y
|
||||
glfw_wayland_inject_mouse_motion_absolute(abs_x, abs_y, SCREEN_WIDTH, SCREEN_HEIGHT)
|
||||
|
||||
|
||||
def click_mouse() -> None:
|
||||
glfw_wayland_inject_mouse_button(MOUSE_BUTTON_LEFT, PRESS)
|
||||
time.sleep(0.05)
|
||||
glfw_wayland_inject_mouse_button(MOUSE_BUTTON_LEFT, RELEASE)
|
||||
|
||||
|
||||
def remote_control(*args: str) -> None:
|
||||
subprocess.run(['kitten', '@', '--use-password=never', '--to', f'unix:{_kitty_socket}'] + list(args), check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def key_event(key: int) -> None:
|
||||
glfw_wayland_inject_key(key, PRESS)
|
||||
time.sleep(0.02)
|
||||
glfw_wayland_inject_key(key, RELEASE)
|
||||
|
||||
|
||||
def send_text(text: str) -> None:
|
||||
remote_control('send-text', text)
|
||||
|
||||
|
||||
def cursor_trail(window_id: str, geometry: tuple[int, int, int, int]) -> None:
|
||||
send_text('gg10j')
|
||||
time.sleep(0.3)
|
||||
send_text('^')
|
||||
time.sleep(0.4)
|
||||
send_text('$')
|
||||
time.sleep(0.3)
|
||||
send_text(':hello world')
|
||||
time.sleep(0.5)
|
||||
key_event(KEY_ESCAPE)
|
||||
time.sleep(0.2)
|
||||
send_text('$')
|
||||
|
||||
|
||||
def cursor_trail_motion_blur(window_id: str, geometry: tuple[int, int, int, int]) -> None:
|
||||
# Long, fast, diagonal jumps are where motion blur is most visible
|
||||
for keys, delay in (('gg0', 0.3), ('L$', 0.45), ('H', 0.45), ('M^', 0.4), ('L0', 0.45), ('H$', 0.45), ('M', 0.4), ('gg0', 0.3)):
|
||||
send_text(keys)
|
||||
time.sleep(delay)
|
||||
|
||||
|
||||
def pond_ripple(window_id: str, geometry: tuple[int, int, int, int]) -> None:
|
||||
time.sleep(0.1)
|
||||
move_mouse(geometry, 100, 100)
|
||||
click_mouse()
|
||||
time.sleep(1)
|
||||
move_mouse(geometry, 200, 200)
|
||||
click_mouse()
|
||||
|
||||
|
||||
def spotlight(window_id: str, geometry: tuple[int, int, int, int]) -> None:
|
||||
width, height = geometry[2], geometry[3]
|
||||
cx, cy = width // 2, height // 2
|
||||
radius_x = width * 0.35
|
||||
radius_y = height * 0.35
|
||||
duration = 3.0
|
||||
fps = 60
|
||||
dt = 1.0 / fps
|
||||
t = 0.0
|
||||
while t < duration:
|
||||
angle = 2 * math.pi * (t / duration)
|
||||
x = int(cx + radius_x * math.cos(angle))
|
||||
y = int(cy + radius_y * math.sin(angle))
|
||||
move_mouse(geometry, x, y)
|
||||
time.sleep(dt)
|
||||
t += dt
|
||||
|
||||
|
||||
def window_focus(window_id: str, geometry: tuple[int, int, int, int]) -> None:
|
||||
time.sleep(0.2)
|
||||
remote_control('focus-window', '-m', 'id:2')
|
||||
time.sleep(1)
|
||||
remote_control('focus-window', '-m', 'id:3')
|
||||
time.sleep(1)
|
||||
remote_control('focus-window', '-m', 'id:1')
|
||||
|
||||
|
||||
def tab_change(window_id: str, geometry: tuple[int, int, int, int]) -> None:
|
||||
time.sleep(0.2)
|
||||
remote_control('focus-tab', '-m', 'id:2')
|
||||
time.sleep(1.5)
|
||||
remote_control('focus-tab', '-m', 'id:1')
|
||||
|
||||
|
||||
metadata: dict[str, dict[str, Any]] = {
|
||||
# Background
|
||||
'inside-the-matrix': {'category': 'background', 'tagline': 'See the bones of reality.'},
|
||||
'northern-lights': {'category': 'background', 'tagline': 'The ethereal Aurora Borealis.', 'cmd': []},
|
||||
'fireworks': {'category': 'background', 'tagline': 'Celebrate the sheer awesomeness of your terminal.'},
|
||||
'water': {'category': 'background', 'tagline': 'Pretend you are cool enough to code underwater.'},
|
||||
# Mouse
|
||||
'pond-ripple': {'animate': pond_ripple, 'category': 'mouse', 'tagline': 'Clicking is like throwing stones in a pond.'},
|
||||
'spotlight': {'animate': spotlight, 'category': 'mouse', 'tagline': 'Spotlight your mouse pointer as it moves around.'},
|
||||
# Cursor trail
|
||||
'cursor-trail-motion-blur': {
|
||||
'animate': cursor_trail_motion_blur,
|
||||
'duration': 4,
|
||||
'initial_sleep': 4,
|
||||
'category': 'cursor-trail',
|
||||
'tagline': 'Make the cursor trail glide smoothly, like a fast moving object caught on camera.',
|
||||
},
|
||||
'cursor-trail-blaze': {'animate': cursor_trail, 'category': 'cursor-trail', 'tagline': 'Set your cursor on fire as it moves around.'},
|
||||
'cursor-trail-lightning': {'animate': cursor_trail, 'category': 'cursor-trail', 'tagline': 'Make your cursor shoot lightning as it moves around.'},
|
||||
'cursor-trail-railgun': {'animate': cursor_trail, 'category': 'cursor-trail', 'tagline': 'Fire a spiral of particles as your cursor moves around.'},
|
||||
'cursor-trail-torpedo': {'animate': cursor_trail, 'category': 'cursor-trail', 'tagline': 'Leave a wake of particles behind your cursor as it moves.'},
|
||||
'cursor-trail-pixiedust': {'animate': cursor_trail, 'category': 'cursor-trail', 'tagline': 'Sprinkle glittering pixie dust as your cursor moves around.'},
|
||||
# Navigation
|
||||
'dim-inactive-windows': {
|
||||
'animate': window_focus,
|
||||
'category': 'navigation',
|
||||
'tagline': 'Make the active window standout more.',
|
||||
'session': 'launch kitten run-shell ls -l\nlaunch kitten run-shell bat -P setup.py\nlaunch kitten run-shell echo Hello World',
|
||||
},
|
||||
'tab-change': {
|
||||
'animate': tab_change,
|
||||
'category': 'navigation',
|
||||
'tagline': 'Highlight the active window on focus change.',
|
||||
'session': 'new_tab My Shell\nlaunch kitten run-shell ls\nnew_tab My Code\nlaunch nvim -R {self}',
|
||||
},
|
||||
'focus-highlight': {
|
||||
'animate': window_focus,
|
||||
'category': 'navigation',
|
||||
'tagline': 'Briefly highlight the active window on focus change.',
|
||||
'session': 'launch kitten run-shell ls -l\nlaunch kitten run-shell bat -P setup.py\nlaunch kitten run-shell echo Hello World',
|
||||
},
|
||||
# Retro terminals
|
||||
'crt': {'category': 'retro', 'title': 'Cathode Ray Tube', 'tagline': 'Your terminal deserves to have curves.', 'duration': 2},
|
||||
'crt-blue': {'category': 'retro', 'title': 'CRT Blue', 'tagline': 'Do you have the blues?', 'duration': 2},
|
||||
'tft': {'category': 'retro', 'title': 'Thin Film LCD', 'tagline': 'You are too modern for CRT', 'duration': 2},
|
||||
}
|
||||
|
||||
|
||||
def wait_for_file(path: str, timeout: float = 10.0) -> bool:
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if os.path.exists(path):
|
||||
return True
|
||||
time.sleep(0.1)
|
||||
return False
|
||||
|
||||
|
||||
def start_sway(config_file: str) -> tuple['subprocess.Popen[bytes]', str, str]:
|
||||
"""Start a headless sway compositor. Returns (proc, wayland_display_name, ipc_socket_path)."""
|
||||
runtime_dir = get_runtime_dir()
|
||||
# Snapshot existing sockets before starting so we can identify the new one
|
||||
existing = set(glob.glob(f'{runtime_dir}/wayland-[0-9]*'))
|
||||
env: dict[str, str] = {k: v for k, v in os.environ.items()}
|
||||
env['WLR_BACKENDS'] = 'headless'
|
||||
# Remove parent display to avoid nested-compositor confusion
|
||||
env.pop('WAYLAND_DISPLAY', None)
|
||||
env.pop('DISPLAY', None)
|
||||
proc = subprocess.Popen(
|
||||
['sway', '--config', config_file],
|
||||
env=env,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
text=False,
|
||||
)
|
||||
# Wait for sway to create its Wayland socket
|
||||
deadline = time.monotonic() + 10
|
||||
wayland_display = ''
|
||||
while time.monotonic() < deadline:
|
||||
current = set(glob.glob(f'{runtime_dir}/wayland-[0-9]*'))
|
||||
for path in sorted(current - existing):
|
||||
if not path.endswith('.lock'):
|
||||
wayland_display = os.path.basename(path)
|
||||
break
|
||||
if wayland_display:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
if not wayland_display:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
raise SystemExit('Timed out waiting for headless sway Wayland socket')
|
||||
# IPC socket path: $XDG_RUNTIME_DIR/sway-ipc.$UID.$PID.sock
|
||||
ipc_socket = os.path.join(runtime_dir, f'sway-ipc.{os.getuid()}.{proc.pid}.sock')
|
||||
if not wait_for_file(ipc_socket, timeout=10):
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
raise SystemExit(f'Timed out waiting for sway IPC socket: {ipc_socket}')
|
||||
return proc, wayland_display, ipc_socket
|
||||
|
||||
|
||||
def record_output(m: dict[str, Any], output_filename: str, wayland_env: dict[str, str]) -> str:
|
||||
duration_seconds = m.get('duration', DEFAULT_DURATION)
|
||||
output_filename += '.mkv'
|
||||
with suppress(FileNotFoundError):
|
||||
os.remove(output_filename)
|
||||
cmd = ['wf-recorder', '-o', 'HEADLESS-1', '-f', output_filename, '-y']
|
||||
# lossless recording
|
||||
cmd += '-c libx264rgb -p crf=0'.split()
|
||||
env = {**os.environ, **wayland_env}
|
||||
try:
|
||||
print(f'🎬 Starting recording for {duration_seconds} seconds...')
|
||||
process = subprocess.Popen(cmd, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
time.sleep(duration_seconds)
|
||||
print('🛑 Stopping recording and saving file...')
|
||||
process.send_signal(signal.SIGINT)
|
||||
# wf-recorder only exits after receiving a new frame, so generate
|
||||
# screen damage until it does
|
||||
for i in range(300):
|
||||
try:
|
||||
process.wait(timeout=0.1)
|
||||
break
|
||||
except subprocess.TimeoutExpired:
|
||||
move_mouse((0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), i % 2, 0)
|
||||
else:
|
||||
process.kill()
|
||||
raise SystemExit('❌ wf-recorder failed to exit')
|
||||
return output_filename
|
||||
except FileNotFoundError:
|
||||
raise SystemExit("❌ Error: 'wf-recorder' is not installed or not in your PATH.")
|
||||
except Exception as e:
|
||||
raise SystemExit(f'❌ An error occurred: {e}')
|
||||
|
||||
|
||||
def drive_loop(kitty: 'subprocess.Popen[bytes]', which: str, m: dict[str, Any], destdir: str, wayland_env: dict[str, str]) -> None:
|
||||
st = m.get('initial_sleep', DEFAULT_INITIAL_SLEEP)
|
||||
print(f'Waiting for {st} seconds before recording...')
|
||||
time.sleep(st)
|
||||
geometry = (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
|
||||
output_file = os.path.join(destdir, which)
|
||||
animate = m.get('animate')
|
||||
if animate is not None:
|
||||
t = Thread(target=animate, args=('', geometry), daemon=True)
|
||||
t.start()
|
||||
lossless_file = record_output(m, output_file, wayland_env)
|
||||
if animate is not None:
|
||||
t.join()
|
||||
kitty.terminate()
|
||||
kitty.wait()
|
||||
print('Transcoding saved recording...')
|
||||
try:
|
||||
for fmt, cmd in {'webm': '-r 60 -c:v libsvtav1 -preset 6 -crf 35 -pix_fmt yuv420p -svtav1-params tune=0 -g 99999'}.items():
|
||||
of = f'{output_file}.{fmt}'
|
||||
with suppress(FileNotFoundError):
|
||||
os.remove(of)
|
||||
# subprocess.run(['mpv', lossless_file])
|
||||
cp = subprocess.run(['ffmpeg', '-i', lossless_file] + cmd.split() + [of], capture_output=True)
|
||||
if cp.returncode != 0:
|
||||
sys.stderr.buffer.write(cp.stderr)
|
||||
raise SystemExit(cp.returncode)
|
||||
print(f'Recording saved: {of}')
|
||||
subprocess.run(['ls', '-sh', of])
|
||||
finally:
|
||||
os.remove(lossless_file)
|
||||
|
||||
|
||||
def get_destdir() -> str:
|
||||
self = os.path.abspath(__file__)
|
||||
d = os.path.dirname
|
||||
return os.path.join(d(d(d(d(self)))), '.cache', 'custom-shader-demos')
|
||||
|
||||
|
||||
def do_one(which: str) -> None:
|
||||
global _sway_socket, _wayland_display, _kitty_socket
|
||||
print('Generating demo video for custon shader:', which)
|
||||
self = os.path.abspath(__file__)
|
||||
destdir = get_destdir()
|
||||
m = metadata.get(which) or {}
|
||||
cmd = m.get('cmd', ['nvim', '-R', '+1', self])
|
||||
os.makedirs(destdir, exist_ok=True)
|
||||
os.environ.pop('KITTY_PUBLIC_KEY', None)
|
||||
session = m.get('session', '').format(self=self)
|
||||
|
||||
with tempfile.NamedTemporaryFile(mode='w', suffix='.conf', delete=False, prefix='sway-demo-') as f:
|
||||
f.write(SWAY_CONFIG)
|
||||
config_file = f.name
|
||||
|
||||
kitty_socket_path = f'@kitty-custom-shader-demo-{os.getpid()}'
|
||||
|
||||
try:
|
||||
sway_proc, wayland_display, ipc_socket = start_sway(config_file)
|
||||
_sway_socket = ipc_socket
|
||||
_wayland_display = wayland_display
|
||||
_kitty_socket = kitty_socket_path
|
||||
wayland_env = {'WAYLAND_DISPLAY': wayland_display}
|
||||
|
||||
# Connect our virtual pointer and keyboard to the compositor before
|
||||
# starting kitty so the seat advertises pointer and keyboard capability
|
||||
# when kitty creates its wl_pointer and wl_keyboard objects.
|
||||
glfw_wayland_inject_init(glfw_path('wayland'), wayland_display)
|
||||
try:
|
||||
kcmd = [
|
||||
'kitty',
|
||||
'--start-as=fullscreen',
|
||||
'--config=NONE',
|
||||
'-o',
|
||||
'font_size=8',
|
||||
'-o',
|
||||
'cursor_trail=1',
|
||||
'-o',
|
||||
f'custom_shaders={which}',
|
||||
'-o',
|
||||
'allow_remote_control=socket-only',
|
||||
f'--listen-on=unix:{kitty_socket_path}',
|
||||
]
|
||||
kcmd += ['--session=-'] if session else cmd
|
||||
kitty_env: dict[str, str] = {k: v for k, v in os.environ.items()}
|
||||
kitty_env.update(wayland_env)
|
||||
kitty = subprocess.Popen(kcmd, env=kitty_env, text=False, stdin=subprocess.PIPE)
|
||||
assert kitty.stdin is not None
|
||||
kitty.stdin.write(session.encode())
|
||||
kitty.stdin.close()
|
||||
try:
|
||||
drive_loop(kitty, which, m, destdir, wayland_env)
|
||||
finally:
|
||||
if kitty.returncode is None:
|
||||
kitty.terminate()
|
||||
kitty.wait()
|
||||
finally:
|
||||
glfw_wayland_inject_terminate()
|
||||
sway_proc.terminate()
|
||||
with suppress(subprocess.TimeoutExpired):
|
||||
sway_proc.wait(timeout=5)
|
||||
if sway_proc.returncode is None:
|
||||
sway_proc.kill()
|
||||
sway_proc.wait()
|
||||
finally:
|
||||
with suppress(FileNotFoundError):
|
||||
os.remove(config_file)
|
||||
with suppress(FileNotFoundError):
|
||||
os.remove(kitty_socket_path)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if len(sys.argv) < 2:
|
||||
shaders = list(metadata)
|
||||
else:
|
||||
shaders = sys.argv[1:]
|
||||
if shaders == ['upload']:
|
||||
cmd = ['rsync', '--info=progress2', '--checksum', '--compress'] + glob.glob(os.path.join(get_destdir(), '*.webm')) + ['dl1:/srv/download/videos/']
|
||||
print('Uploading changed demo video files...', flush=True)
|
||||
os.execlp(cmd[0], *cmd)
|
||||
try:
|
||||
for which in shaders:
|
||||
do_one(which)
|
||||
except KeyboardInterrupt:
|
||||
raise SystemExit('Aborting on user interrupt')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,11 @@
|
||||
startgroup
|
||||
# static effect, redraw only when the active window changes
|
||||
animation_step 0
|
||||
var float HIGHLIGHT_INTENSITY = 0
|
||||
var float BORDER_WIDTH = 0
|
||||
# do not dim the tab bar and treat the padding/title bar of the active
|
||||
# window as part of it, so it is not surrounded by a dimmed frame
|
||||
var bool DIM_CENTRAL_AREA_ONLY = true
|
||||
var bool INCLUDE_WINDOW_PADDING = true
|
||||
shaders focus-highlight
|
||||
endgroup
|
||||
@@ -0,0 +1,5 @@
|
||||
startgroup
|
||||
animation_start os-window-focus-in | user-activity
|
||||
animation_stop os-window-focus-out | user-idle
|
||||
shaders fireworks-rockets
|
||||
endgroup
|
||||
@@ -0,0 +1,126 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Fireworks with Rockets — port of https://www.shadertoy.com/view/4dBGRw
|
||||
// Ported to Slang for kitty custom shader system
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
static const int NUM_PARTICLES = 128;
|
||||
static const float BLACK_BLEND_THRESHOLD = 0.4f;
|
||||
static const float CYCLE_TIME = 6.0f;
|
||||
static const float PARTICLE_PHASE = 2.0f;
|
||||
|
||||
// Pseudo-random in [-1, 1]
|
||||
float
|
||||
rand_val(float val, float seed) {
|
||||
return cos(val * sin(val * seed) * seed);
|
||||
}
|
||||
|
||||
float
|
||||
distance2(float2 a, float2 b) {
|
||||
float2 d = a - b;
|
||||
return dot(d, d);
|
||||
}
|
||||
|
||||
// Diagonal red-and-white barber-pole pattern — branchless
|
||||
float3
|
||||
barberpole(float2 pos, float2 rocketpos) {
|
||||
float d = fmod(((pos.x - rocketpos.x) + (pos.y - rocketpos.y)) * 20.0f, 2.0f);
|
||||
return lerp(float3(1.0f), float3(1.0f, 0.0f, 0.0f), step(1.0f, d));
|
||||
}
|
||||
|
||||
// Draw a single rocket at rocketpos in the supplied coordinate space — branchless
|
||||
float3
|
||||
rocket(float2 pos, float2 rocketpos) {
|
||||
float3 col = float3(0.0f);
|
||||
float absx = abs(rocketpos.x - pos.x);
|
||||
float absy = abs(rocketpos.y - pos.y);
|
||||
|
||||
// Wooden stick
|
||||
float stick = step(absx, 0.01f) * step(absy, 0.22f);
|
||||
col = lerp(col, float3(1.0f, 0.5f, 0.5f), stick);
|
||||
|
||||
// Barber-pole body
|
||||
float pole = step(absx, 0.05f) * step(absy, 0.15f);
|
||||
col = lerp(col, barberpole(pos, rocketpos), pole);
|
||||
|
||||
// Pointed nose cone
|
||||
float pointw = (rocketpos.y - pos.y - 0.25f) * -0.7f;
|
||||
float has_point = step(0.1f, rocketpos.y - pos.y);
|
||||
float f_point = smoothstep(pointw - 0.001f, pointw + 0.001f, absx);
|
||||
col = lerp(col, lerp(float3(1.0f, 0.0f, 0.0f), col, f_point), has_point);
|
||||
|
||||
// Ambient shadow gradient
|
||||
float shadow = -0.5f + smoothstep(-0.05f, 0.05f, rocketpos.x - pos.x);
|
||||
col *= 0.7f + shadow;
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
// Draw the exploding particle burst.
|
||||
// Particle direction for iteration i is the unit vector at angle i radians,
|
||||
// precomputed as (cos(i), sin(i)) — equivalent to iteratively applying the
|
||||
// original 1-radian rotation matrix but eliminates inter-iteration data dependency.
|
||||
float3
|
||||
drawParticles(float2 pos, float3 particolor, float time, float2 cpos, float gravity, float seed, float timelength) {
|
||||
float3 col = float3(0.0f);
|
||||
|
||||
[ForceUnroll]
|
||||
for (int i = 0; i < NUM_PARTICLES; i++) {
|
||||
float fi = float(i + 1); // 1-indexed to match original
|
||||
float d = rand_val(fi, seed);
|
||||
float fade = (fi / float(NUM_PARTICLES)) * time;
|
||||
float2 pp = float2(cos(float(i)), sin(float(i))); // unit direction at angle i
|
||||
float2 particpos = cpos + time * pp * d;
|
||||
col = lerp(particolor / fade, col, smoothstep(0.0f, 0.0001f, distance2(particpos, pos)));
|
||||
}
|
||||
col *= smoothstep(0.0f, 1.0f, (timelength - time) / timelength);
|
||||
return col;
|
||||
}
|
||||
|
||||
// Returns rocket or particles depending on which phase of the cycle we are in
|
||||
float3
|
||||
drawFireworks(float time, float2 uv, float3 particolor, float seed) {
|
||||
float3 col = float3(0.0f);
|
||||
if (time <= 0.0f) return col;
|
||||
|
||||
float tmod = fmod(time, CYCLE_TIME);
|
||||
float cycle_id = ceil(time / CYCLE_TIME);
|
||||
|
||||
if (tmod > PARTICLE_PHASE) {
|
||||
float2 cpos = float2(rand_val(cycle_id, seed), -0.5f);
|
||||
col = drawParticles(uv, particolor, tmod - PARTICLE_PHASE, cpos, 0.5f, cycle_id, seed);
|
||||
} else {
|
||||
float rx = 3.0f * rand_val(cycle_id, seed);
|
||||
float ry = 3.0f * (-0.5f + (PARTICLE_PHASE - tmod));
|
||||
col = rocket(uv * 3.0f, float2(rx, ry));
|
||||
}
|
||||
return col;
|
||||
}
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
float2 pixelDims = float2(d.viewport_size_pixels) * t.viewport.zw;
|
||||
float aspect = pixelDims.x / pixelDims.y;
|
||||
|
||||
// Map to [-aspect, aspect] × [-1, 1] with y=1 at top (matching the original)
|
||||
float2 uv = 1.0f - 2.0f * t.pos;
|
||||
uv.x *= aspect;
|
||||
uv.y = -uv.y;
|
||||
|
||||
float3 col = float3(0.1f, 0.1f, 0.2f);
|
||||
col += 0.1f * uv.y; // subtle sky gradient
|
||||
|
||||
float time = d.wrapped_time(3600u);
|
||||
col += drawFireworks(time, uv, float3(1.0f, 0.1f, 0.1f), 1.0f);
|
||||
col += drawFireworks(time - 2.0f, uv, float3(0.0f, 1.0f, 0.5f), 2.0f);
|
||||
col += drawFireworks(time - 4.0f, uv, float3(1.0f, 1.0f, 0.1f), 3.0f);
|
||||
|
||||
float4 terminalColor = t.backbuffer.Sample(t.pos);
|
||||
float alpha = step(length(terminalColor.rgb), BLACK_BLEND_THRESHOLD);
|
||||
float3 blended = lerp(terminalColor.rgb, col * 0.3f, alpha);
|
||||
|
||||
return float4(blended, terminalColor.a);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
startgroup
|
||||
animation_start os-window-focus-in | user-activity
|
||||
animation_stop os-window-focus-out | user-idle
|
||||
shaders fireworks
|
||||
endgroup
|
||||
@@ -0,0 +1,108 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Fireworks shader — port of https://www.shadertoy.com/view/lscGRl
|
||||
// "Fireworks" by Martijn Steinrucken aka BigWings - 2015
|
||||
// License: Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
static const int NUM_EXPLOSIONS = 3;
|
||||
static const int NUM_PARTICLES = 42;
|
||||
static const float BLACK_BLEND_THRESHOLD = 0.4f;
|
||||
static const float TIME_SCALE = 0.5f;
|
||||
static const float PI = 3.14159265359f;
|
||||
|
||||
// Noise constant from Dave Hoskins — not user-tunable so kept as plain static const
|
||||
static const float3 MOD3 = float3(0.1031f, 0.11369f, 0.13787f);
|
||||
|
||||
float3
|
||||
hash31(float p) {
|
||||
float3 p3 = frac(float3(p) * MOD3);
|
||||
p3 += dot(p3, p3.yzx + 19.19f);
|
||||
return frac(float3((p3.x + p3.y) * p3.z, (p3.x + p3.z) * p3.y, (p3.y + p3.z) * p3.x));
|
||||
}
|
||||
|
||||
float
|
||||
hash12(float2 p) {
|
||||
float3 p3 = frac(float3(p.xyx) * MOD3);
|
||||
p3 += dot(p3, p3.yzx + 19.19f);
|
||||
return frac((p3.x + p3.y) * p3.z);
|
||||
}
|
||||
|
||||
float
|
||||
light(float2 uv, float2 pos, float size) {
|
||||
uv -= pos;
|
||||
size *= size;
|
||||
return size / dot(uv, uv);
|
||||
}
|
||||
|
||||
float3
|
||||
explosion(float2 uv, float2 p, float seed, float t) {
|
||||
float3 col = float3(0.0f);
|
||||
float3 en = hash31(seed);
|
||||
float3 baseCol = en;
|
||||
|
||||
// startP, pt, and b are loop-invariant; computed once outside
|
||||
float2 startP = p - float2(0.0f, t * t * 0.1f);
|
||||
float pt = 1.0f - pow(t - 1.0f, 2.0f);
|
||||
// B(en.x, en.y, en.z, t) macro expansion
|
||||
float b = smoothstep(en.x - en.z, en.x + en.z, t) * smoothstep(en.y + en.z, en.y - en.z, t);
|
||||
float sizeBase = lerp(0.01f, 0.005f, smoothstep(0.0f, 0.1f, pt)) * smoothstep(1.0f, 0.1f, pt);
|
||||
|
||||
[ForceUnroll]
|
||||
for (int i = 0; i < NUM_PARTICLES; i++) {
|
||||
float3 n = hash31(float(i)) - 0.5f;
|
||||
float2 endP = startP + normalize(n.xy) * n.z - float2(0.0f, t * 0.2f);
|
||||
float2 pos = lerp(p, endP, pt);
|
||||
|
||||
float sparkle = sin((pt + n.z) * 21.0f) * 0.5f + 0.5f;
|
||||
sparkle = pow(sparkle, pow(en.x, 3.0f) * 50.0f) * lerp(0.01f, 0.01f, en.y * n.y);
|
||||
|
||||
col += baseCol * light(uv, pos, sizeBase + sparkle * b);
|
||||
}
|
||||
return col;
|
||||
}
|
||||
|
||||
float3
|
||||
rainbow(float3 c, float time) {
|
||||
float avg = (c.r + c.g + c.b) / 3.0f;
|
||||
c = avg + (c - avg) * sin(float3(0.0f, 0.333f, 0.666f) + time);
|
||||
c += sin(float3(0.4f, 0.3f, 0.3f) * time + float3(1.1244f, 3.43215f, 6.435f)) * float3(0.4f, 0.1f, 0.5f);
|
||||
return c;
|
||||
}
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
float2 pixelDims = float2(d.viewport_size_pixels) * t.viewport.zw;
|
||||
float aspect = pixelDims.x / pixelDims.y;
|
||||
float time = d.wrapped_time(3600u) * TIME_SCALE;
|
||||
|
||||
// Aspect-corrected UV with y=0 at top so gravity points downward
|
||||
float2 uv = t.pos;
|
||||
uv.x -= 0.5f;
|
||||
uv.x *= aspect;
|
||||
uv.y = -uv.y + 1.0f;
|
||||
|
||||
float3 c = float3(0.0f);
|
||||
|
||||
[ForceUnroll]
|
||||
for (int i = 0; i < NUM_EXPLOSIONS; i++) {
|
||||
float et = time + float(i) * 1234.45235f;
|
||||
float id = floor(et);
|
||||
et -= id;
|
||||
|
||||
float2 p = hash31(id).xy;
|
||||
p.x -= 0.5f;
|
||||
p.x *= 1.6f;
|
||||
c += explosion(uv, p, id, et);
|
||||
}
|
||||
c = rainbow(c, d.wrapped_time(3600u));
|
||||
|
||||
float4 terminalColor = t.backbuffer.Sample(t.pos);
|
||||
float alpha = step(length(terminalColor.rgb), BLACK_BLEND_THRESHOLD);
|
||||
float3 blended = lerp(terminalColor.rgb, c * 0.3f, alpha);
|
||||
|
||||
return float4(blended, terminalColor.a);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
startgroup
|
||||
animation_start window-focus-in
|
||||
animation_stop 750
|
||||
animation_curve ease-in
|
||||
animation_step 16
|
||||
shaders focus-highlight
|
||||
endgroup
|
||||
@@ -0,0 +1,66 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Focus highlight effect
|
||||
// Briefly illuminates the active window whenever it gains focus, then fades out.
|
||||
// Uses d.active_window_geometry to locate the window bounds in UV space.
|
||||
// animation_progress (0 → 1) drives the fade over the pipeline duration.
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
// Brightness multiplier boost applied to content inside the active window.
|
||||
// 0.0 = no boost, 0.15 = 15% brighter.
|
||||
static const float HIGHLIGHT_INTENSITY = 0.30;
|
||||
// Width of the inner border glow in UV units.
|
||||
static const float BORDER_WIDTH = 0.04;
|
||||
// Peak additive brightness multiplier at the window border edge.
|
||||
static const float BORDER_GLOW = 0.55;
|
||||
// Fraction of the original color retained outside the active window (1.0 = unchanged, 0.0 = blend target).
|
||||
static const float INACTIVE_DIM = 0.3;
|
||||
// Blend target in linear RGB; black preserves the original dimming behavior.
|
||||
static const float3 INACTIVE_DIM_COLOR = float3(0.0);
|
||||
// Keep the tab bar outside the effect when requested by a pipeline.
|
||||
static const bool DIM_CENTRAL_AREA_ONLY = false;
|
||||
// Include the active window's title bar, margin, border and padding in its unchanged/highlighted area.
|
||||
static const bool INCLUDE_WINDOW_PADDING = false;
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
if (DIM_CENTRAL_AREA_ONLY) {
|
||||
float4 area = d.central_area;
|
||||
if (any(t.pos < area.xy) || any(t.pos > area.xy + area.zw)) return color;
|
||||
}
|
||||
float4 g = d.active_window_geometry;
|
||||
// Pass through unchanged if no active window geometry is known.
|
||||
if (g.z <= 0.0 || g.w <= 0.0) return color;
|
||||
if (INCLUDE_WINDOW_PADDING) {
|
||||
g.xy -= d.active_window_padding.xy;
|
||||
g.zw += d.active_window_padding.xy + d.active_window_padding.zw;
|
||||
}
|
||||
|
||||
float2 uv = t.pos;
|
||||
float2 winMin = g.xy;
|
||||
float2 winMax = g.xy + g.zw;
|
||||
|
||||
// Effect strength decays from 1 at animation start to 0 at the end.
|
||||
float strength = 1.0 - t.animation_progress;
|
||||
|
||||
bool inWindow = all(uv >= winMin) && all(uv <= winMax);
|
||||
|
||||
if (inWindow) {
|
||||
if (HIGHLIGHT_INTENSITY == 0 && BORDER_WIDTH == 0) return color;
|
||||
// Minimum distance from this pixel to any edge of the active window.
|
||||
float2 edgeDists = min(uv - winMin, winMax - uv);
|
||||
float nearestEdge = min(edgeDists.x, edgeDists.y);
|
||||
|
||||
// Additive border glow: strongest at the edge, falls off over BORDER_WIDTH.
|
||||
float borderGlow = smoothstep(BORDER_WIDTH, 0.0, nearestEdge) * BORDER_GLOW;
|
||||
|
||||
float boost = (HIGHLIGHT_INTENSITY + borderGlow) * strength;
|
||||
return float4(color.rgb * (1.0 + boost), color.a);
|
||||
}
|
||||
// Slightly dim inactive areas to draw the eye to the focused window.
|
||||
float dim = lerp(1.0, INACTIVE_DIM, strength);
|
||||
return float4(lerp(INACTIVE_DIM_COLOR, color.rgb, dim), color.a);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
startgroup
|
||||
animation_start os-window-focus-in | user-activity
|
||||
animation_stop os-window-focus-out | user-idle
|
||||
shaders inside-the-matrix
|
||||
endgroup
|
||||
@@ -0,0 +1,373 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Inside the Matrix https://www.shadertoy.com/view/4t3BWl
|
||||
// runes code by FabriceNeyret2 / otaviogood (https://www.shadertoy.com/view/4ltyDM)
|
||||
// Ported to Slang for kitty custom shader system
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
static const int ITERATIONS = 40;
|
||||
static const float SPEED = 0.5f;
|
||||
static const float STRIP_CHARS_MIN = 7.0f;
|
||||
static const float STRIP_CHARS_MAX = 40.0f;
|
||||
static const float STRIP_CHAR_HEIGHT = 0.15f;
|
||||
static const float STRIP_CHAR_WIDTH = 0.10f;
|
||||
static const float ZCELL_SIZE = STRIP_CHAR_HEIGHT * STRIP_CHARS_MAX;
|
||||
static const float XYCELL_SIZE = 12.0f * STRIP_CHAR_WIDTH;
|
||||
static const int BLOCK_SIZE = 10;
|
||||
static const int BLOCK_GAP = 2;
|
||||
static const float WALK_SPEED = 0.5f * XYCELL_SIZE;
|
||||
static const float BLOCKS_BEFORE_TURN = 3.0f;
|
||||
static const float PI = 3.14159265359f;
|
||||
|
||||
// ---- random ----
|
||||
|
||||
float
|
||||
hash(float v) {
|
||||
return frac(sin(v) * 43758.5453123f);
|
||||
}
|
||||
|
||||
float
|
||||
hash(float2 v) {
|
||||
return hash(dot(v, float2(5.3983f, 5.4427f)));
|
||||
}
|
||||
|
||||
float2
|
||||
hash2(float2 v) {
|
||||
// GLSL: v * mat2(127.1, 311.7, 269.5, 183.3) [column-major]
|
||||
// Slang float2x2 is row-major; transpose the GLSL column-major layout.
|
||||
v = mul(v, float2x2(127.1f, 269.5f, 311.7f, 183.3f));
|
||||
return frac(sin(v) * 43758.5453123f);
|
||||
}
|
||||
|
||||
float4
|
||||
hash4(float2 v) {
|
||||
// GLSL: v * mat4x2(127.1,311.7, 269.5,183.3, 113.5,271.9, 246.1,124.6)
|
||||
// mat4x2 = 4 cols × 2 rows; transpose into float2x4 (2 rows × 4 cols).
|
||||
float4 p = mul(v, float2x4(127.1f, 269.5f, 113.5f, 246.1f, 311.7f, 183.3f, 271.9f, 124.6f));
|
||||
return frac(sin(p) * 43758.5453123f);
|
||||
}
|
||||
|
||||
float4
|
||||
hash4(float3 v) {
|
||||
// GLSL: v * mat4x3(127.1,311.7,74.7, 269.5,183.3,246.1, 113.5,271.9,124.6, 271.9,269.5,311.7)
|
||||
// mat4x3 = 4 cols × 3 rows; transpose into float3x4 (3 rows × 4 cols).
|
||||
float4 p = mul(v, float3x4(127.1f, 269.5f, 113.5f, 271.9f, 311.7f, 183.3f, 271.9f, 269.5f, 74.7f, 246.1f, 124.6f, 311.7f));
|
||||
return frac(sin(p) * 43758.5453123f);
|
||||
}
|
||||
|
||||
// ---- symbols ----
|
||||
|
||||
float
|
||||
rune_line(float2 p, float2 a, float2 b) {
|
||||
p -= a;
|
||||
b -= a;
|
||||
float h = clamp(dot(p, b) / dot(b, b), 0.0f, 1.0f);
|
||||
return length(p - b * h);
|
||||
}
|
||||
|
||||
float
|
||||
rune(float2 U, float2 seed, float highlight) {
|
||||
float d = 1e5f;
|
||||
[ForceUnroll]
|
||||
for (int i = 0; i < 4; i++) {
|
||||
float4 pos = hash4(seed);
|
||||
seed += 1.0f;
|
||||
|
||||
// each rune touches the edge of its box on all 4 sides
|
||||
// with [ForceUnroll] these become compile-time constant selects
|
||||
pos.y = (i == 0) ? 0.0f : pos.y;
|
||||
pos.x = (i == 1) ? 0.999f : pos.x;
|
||||
pos.x = (i == 2) ? 0.0f : pos.x;
|
||||
pos.y = (i == 3) ? 0.999f : pos.y;
|
||||
|
||||
float4 snaps = float4(2.0f, 3.0f, 2.0f, 3.0f);
|
||||
pos = (floor(pos * snaps) + 0.5f) / snaps;
|
||||
|
||||
if (any(pos.xy != pos.zw)) d = min(d, rune_line(U, pos.xy, pos.zw + 0.001f));
|
||||
}
|
||||
return smoothstep(0.1f, 0.0f, d) + highlight * smoothstep(0.4f, 0.0f, d);
|
||||
}
|
||||
|
||||
float
|
||||
random_char(float2 outer, float2 inner, float highlight) {
|
||||
float2 seed = float2(dot(outer, float2(269.5f, 183.3f)), dot(outer, float2(113.5f, 271.9f)));
|
||||
return rune(inner, seed, highlight);
|
||||
}
|
||||
|
||||
// ---- digital rain ----
|
||||
|
||||
float3
|
||||
rain(float3 ro3, float3 rd3, float time) {
|
||||
float4 result = float4(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
|
||||
float2 ro2 = ro3.xy;
|
||||
float2 rd2 = normalize(rd3.xy);
|
||||
|
||||
bool prefer_dx = abs(rd2.x) > abs(rd2.y);
|
||||
float t3_to_t2 = prefer_dx ? rd3.x / rd2.x : rd3.y / rd2.y;
|
||||
|
||||
int3 cell_side = int3(step(0.0f, rd3));
|
||||
int3 cell_shift = int3(sign(rd3));
|
||||
|
||||
float t2 = 0.0f;
|
||||
int2 next_cell = int2(floor(ro2 / XYCELL_SIZE));
|
||||
|
||||
[ForceUnroll]
|
||||
for (int iter = 0; iter < ITERATIONS; iter++) {
|
||||
int2 cell = next_cell;
|
||||
float t2s = t2;
|
||||
|
||||
float2 side = float2(next_cell + cell_side.xy) * XYCELL_SIZE;
|
||||
float2 t2_side = (side - ro2) / rd2;
|
||||
|
||||
// branchless cell-side selection
|
||||
bool pick_x = t2_side.x < t2_side.y;
|
||||
t2 = pick_x ? t2_side.x : t2_side.y;
|
||||
next_cell.x += pick_x ? cell_shift.x : 0;
|
||||
next_cell.y += pick_x ? 0 : cell_shift.y;
|
||||
|
||||
// skip gap cells
|
||||
float2 cell_in_block = frac(float2(cell) / float(BLOCK_SIZE));
|
||||
float gap = float(BLOCK_GAP) / float(BLOCK_SIZE);
|
||||
if (cell_in_block.x < gap || cell_in_block.y < gap || (cell_in_block.x < (gap + 0.1f) && cell_in_block.y < (gap + 0.1f))) continue;
|
||||
|
||||
float t3s = t2s / t3_to_t2;
|
||||
float pos_z = ro3.z + rd3.z * t3s;
|
||||
float xh = hash(float2(cell));
|
||||
float z_shift = xh * 11.0f - time * (0.5f + xh + xh * xh + pow(xh, 16.0f) * 3.0f);
|
||||
float czs = floor(z_shift / STRIP_CHAR_HEIGHT);
|
||||
z_shift = czs * STRIP_CHAR_HEIGHT;
|
||||
int zcell = int(floor((pos_z - z_shift) / ZCELL_SIZE));
|
||||
|
||||
[ForceUnroll]
|
||||
for (int j = 0; j < 2; j++) {
|
||||
float4 ch = hash4(float3(int3(cell, zcell)));
|
||||
float4 ch2 = frac(ch * float4(127.1f, 311.7f, 271.9f, 124.6f));
|
||||
|
||||
float chars_count = ch.w * (STRIP_CHARS_MAX - STRIP_CHARS_MIN) + STRIP_CHARS_MIN;
|
||||
float target_length = chars_count * STRIP_CHAR_HEIGHT;
|
||||
float target_rad = STRIP_CHAR_WIDTH * 0.5f;
|
||||
float target_z = float(zcell) * ZCELL_SIZE + z_shift + ch.z * (ZCELL_SIZE - target_length);
|
||||
float2 target = float2(cell) * XYCELL_SIZE + target_rad + ch.xy * (XYCELL_SIZE - target_rad * 2.0f);
|
||||
|
||||
float2 sv = target - ro2;
|
||||
float tmin = dot(sv, rd2);
|
||||
if (tmin >= t2s && tmin <= t2) {
|
||||
float u = sv.x * rd2.y - sv.y * rd2.x;
|
||||
if (abs(u) < target_rad) {
|
||||
u = (u / target_rad + 1.0f) * 0.5f;
|
||||
float z = ro3.z + rd3.z * tmin / t3_to_t2;
|
||||
float v = (z - target_z) / target_length;
|
||||
if (v >= 0.0f && v < 1.0f) {
|
||||
float c = floor(v * chars_count);
|
||||
float q = frac(v * chars_count);
|
||||
float2 char_hash = hash2(float2(c + czs, ch2.x));
|
||||
if (char_hash.x >= 0.1f || c == 0.0f) {
|
||||
float time_factor = floor(c == 0.0f ? time : time * (ch2.z + ch2.w * ch2.w * 4.0f * pow(char_hash.y, 4.0f)));
|
||||
float a = random_char(float2(char_hash.x, time_factor), float2(u, q), max(1.0f, 3.0f - c * 0.5f) * 0.2f);
|
||||
a *= clamp((chars_count - 0.5f - c) * 0.5f, 0.0f, 1.0f);
|
||||
if (a > 0.0f) {
|
||||
float attenuation = 1.0f + pow(0.06f * tmin / t3_to_t2, 2.0f);
|
||||
float3 col = (c == 0.0f ? float3(0.67f, 1.0f, 0.82f) : float3(0.25f, 0.80f, 0.40f)) / attenuation;
|
||||
float a1 = result.a;
|
||||
result.a = a1 + (1.0f - a1) * a;
|
||||
result.xyz = (result.xyz * a1 + col * (1.0f - a1) * a) / result.a;
|
||||
if (result.a > 0.98f) return result.xyz;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
zcell += cell_shift.z;
|
||||
}
|
||||
}
|
||||
return result.xyz * result.a;
|
||||
}
|
||||
|
||||
// ---- camera helpers ----
|
||||
// For M*v in GLSL with column-major constructor, Slang needs the same values
|
||||
// re-read as row-major (i.e. transposed GLSL column-major == correct Slang row-major).
|
||||
|
||||
float2
|
||||
rotate2D(float2 v, float angle) {
|
||||
float s = sin(angle), c = cos(angle);
|
||||
// GLSL: mat2(c,-s, s,c)*v → rows: (c,s),(-s,c)
|
||||
return mul(float2x2(c, s, -s, c), v);
|
||||
}
|
||||
|
||||
float3
|
||||
rotateX(float3 v, float angle) {
|
||||
float s = sin(angle), c = cos(angle);
|
||||
// GLSL: mat3(1,0,0, 0,c,-s, 0,s,c)*v → rows: (1,0,0),(0,c,s),(0,-s,c)
|
||||
return mul(float3x3(1.0f, 0.0f, 0.0f, 0.0f, c, s, 0.0f, -s, c), v);
|
||||
}
|
||||
|
||||
float3
|
||||
rotateY(float3 v, float angle) {
|
||||
float s = sin(angle), c = cos(angle);
|
||||
// GLSL: mat3(c,0,-s, 0,1,0, s,0,c)*v → rows: (c,0,s),(0,1,0),(-s,0,c)
|
||||
return mul(float3x3(c, 0.0f, s, 0.0f, 1.0f, 0.0f, -s, 0.0f, c), v);
|
||||
}
|
||||
|
||||
float3
|
||||
rotateZ(float3 v, float angle) {
|
||||
float s = sin(angle), c = cos(angle);
|
||||
// GLSL: mat3(c,-s,0, s,c,0, 0,0,1)*v → rows: (c,s,0),(-s,c,0),(0,0,1)
|
||||
return mul(float3x3(c, s, 0.0f, -s, c, 0.0f, 0.0f, 0.0f, 1.0f), v);
|
||||
}
|
||||
|
||||
float
|
||||
smoothstep1(float x) {
|
||||
return smoothstep(0.0f, 1.0f, x);
|
||||
}
|
||||
|
||||
// ---- entry point ----
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
float2 uv = t.pos;
|
||||
float time = d.wrapped_time(300u) * SPEED;
|
||||
|
||||
const float turn_rad = 0.25f / BLOCKS_BEFORE_TURN;
|
||||
const float turn_abs_time = (PI * 0.5f * turn_rad) * 1.5f;
|
||||
const float turn_time = turn_abs_time / (1.0f - 2.0f * turn_rad + turn_abs_time);
|
||||
|
||||
float level1_size = float(BLOCK_SIZE) * BLOCKS_BEFORE_TURN * XYCELL_SIZE;
|
||||
float gap_size = float(BLOCK_GAP) * XYCELL_SIZE;
|
||||
|
||||
float3 ro = float3(gap_size * 0.5f, gap_size * 0.5f, 0.0f);
|
||||
float3 rd = float3(uv.x, 2.0f, uv.y);
|
||||
|
||||
float tq = frac(time / (level1_size * 4.0f * 4.0f) * WALK_SPEED);
|
||||
float t8 = frac(tq * 4.0f);
|
||||
float t1 = frac(t8 * 8.0f);
|
||||
|
||||
float2 prev, dir;
|
||||
if (tq < 0.25f) {
|
||||
prev = float2(0.0f, 0.0f);
|
||||
dir = float2(0.0f, 1.0f);
|
||||
} else if (tq < 0.50f) {
|
||||
prev = float2(0.0f, 1.0f);
|
||||
dir = float2(1.0f, 0.0f);
|
||||
} else if (tq < 0.75f) {
|
||||
prev = float2(1.0f, 1.0f);
|
||||
dir = float2(0.0f, -1.0f);
|
||||
} else {
|
||||
prev = float2(1.0f, 0.0f);
|
||||
dir = float2(-1.0f, 0.0f);
|
||||
}
|
||||
|
||||
float angle = floor(tq * 4.0f);
|
||||
prev *= 4.0f;
|
||||
|
||||
const float first_turn_look_angle = 0.4f;
|
||||
const float second_turn_drift_angle = 0.5f;
|
||||
const float fifth_turn_drift_angle = 0.25f;
|
||||
|
||||
float2 dirL = rotate2D(dir, -PI * 0.5f);
|
||||
float2 dirR = -dirL;
|
||||
float2 turn;
|
||||
float turn_sign = 0.0f;
|
||||
float up_down = 0.0f;
|
||||
float rotate_on_turns = 1.0f;
|
||||
float roll_on_turns = 1.0f;
|
||||
float add_angel = 0.0f;
|
||||
|
||||
if (t8 < 0.125f) {
|
||||
turn = dirL;
|
||||
turn_sign = -1.0f;
|
||||
angle -= first_turn_look_angle * (max(0.0f, t1 - (1.0f - turn_time * 2.0f)) / turn_time - max(0.0f, t1 - (1.0f - turn_time)) / turn_time * 2.5f);
|
||||
roll_on_turns = 0.0f;
|
||||
} else if (t8 < 0.250f) {
|
||||
prev += dir;
|
||||
turn = dir;
|
||||
dir = dirL;
|
||||
angle -= 1.0f;
|
||||
turn_sign = 1.0f;
|
||||
add_angel += first_turn_look_angle * 0.5f + (-first_turn_look_angle * 0.5f + 1.0f + second_turn_drift_angle) * t1;
|
||||
rotate_on_turns = 0.0f;
|
||||
roll_on_turns = 0.0f;
|
||||
} else if (t8 < 0.375f) {
|
||||
prev += dir + dirL;
|
||||
turn = dirR;
|
||||
turn_sign = 1.0f;
|
||||
add_angel += second_turn_drift_angle * sqrt(1.0f - t1);
|
||||
} else if (t8 < 0.500f) {
|
||||
prev += dir + dir + dirL;
|
||||
turn = dirR;
|
||||
dir = dirR;
|
||||
angle += 1.0f;
|
||||
turn_sign = 0.0f;
|
||||
up_down = sin(t1 * PI) * 0.37f;
|
||||
} else if (t8 < 0.625f) {
|
||||
prev += dir + dir;
|
||||
turn = dir;
|
||||
dir = dirR;
|
||||
angle += 1.0f;
|
||||
turn_sign = -1.0f;
|
||||
up_down = sin(-min(1.0f, t1 / (1.0f - turn_time)) * PI) * 0.37f;
|
||||
} else if (t8 < 0.750f) {
|
||||
prev += dir + dir + dirR;
|
||||
turn = dirL;
|
||||
turn_sign = -1.0f;
|
||||
add_angel -= (fifth_turn_drift_angle + 1.0f) * smoothstep1(t1);
|
||||
rotate_on_turns = 0.0f;
|
||||
roll_on_turns = 0.0f;
|
||||
} else if (t8 < 0.875f) {
|
||||
prev += dir + dir + dir + dirR;
|
||||
turn = dir;
|
||||
dir = dirL;
|
||||
angle -= 1.0f;
|
||||
turn_sign = 1.0f;
|
||||
add_angel -= fifth_turn_drift_angle - smoothstep1(t1) * (fifth_turn_drift_angle * 2.0f + 1.0f);
|
||||
rotate_on_turns = 0.0f;
|
||||
roll_on_turns = 0.0f;
|
||||
} else {
|
||||
prev += dir + dir + dir;
|
||||
turn = dirR;
|
||||
turn_sign = 1.0f;
|
||||
angle += fifth_turn_drift_angle * (1.5f * min(1.0f, (1.0f - t1) / turn_time) - 0.5f * smoothstep1(1.0f - min(1.0f, t1 / (1.0f - turn_time))));
|
||||
}
|
||||
|
||||
if (d.mouse_button_pressed.x != 0) {
|
||||
float2 mouse = 2.0f * d.mouse_pos.xy - 1.0f;
|
||||
up_down = -0.7f * mouse.y;
|
||||
angle += mouse.x;
|
||||
rotate_on_turns = 1.0f;
|
||||
roll_on_turns = 0.0f;
|
||||
} else {
|
||||
angle += add_angel;
|
||||
}
|
||||
|
||||
rd = rotateX(rd, up_down);
|
||||
|
||||
float2 p;
|
||||
if (turn_sign == 0.0f) {
|
||||
p = prev + dir * (turn_rad + t1);
|
||||
} else if (t1 > (1.0f - turn_time)) {
|
||||
float tr = (t1 - (1.0f - turn_time)) / turn_time;
|
||||
float2 ctr = prev + dir * (1.0f - turn_rad) + turn * turn_rad;
|
||||
p = ctr + turn_rad * rotate2D(dir, (tr - 1.0f) * turn_sign * PI * 0.5f);
|
||||
angle += tr * turn_sign * rotate_on_turns;
|
||||
rd = rotateY(rd, sin(tr * turn_sign * PI) * 0.2f * roll_on_turns);
|
||||
} else {
|
||||
t1 /= (1.0f - turn_time);
|
||||
p = prev + dir * (turn_rad + (1.0f - turn_rad * 2.0f) * t1);
|
||||
}
|
||||
|
||||
rd = rotateZ(rd, angle * PI * 0.5f);
|
||||
ro.xy += level1_size * p;
|
||||
rd = normalize(rd);
|
||||
ro += rd * 0.2f;
|
||||
|
||||
float3 col = rain(ro, rd, time) * 0.25f;
|
||||
|
||||
float4 terminalColor = t.backbuffer.Sample(t.pos);
|
||||
float mask = 1.2f - step(0.5f, dot(terminalColor.rgb, float3(1.0f, 1.0f, 1.0f)));
|
||||
float3 blended = lerp(terminalColor.rgb * 1.2f, col, mask);
|
||||
|
||||
return float4(blended, terminalColor.a);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Color-inversion (negative) effect.
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
return float4(1.0 - color.r, 1.0 - color.g, 1.0 - color.b, color.a);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
textures a persist
|
||||
|
||||
startgroup
|
||||
animation_start os-window-focus-in | user-activity
|
||||
animation_stop os-window-focus-out | user-idle
|
||||
var int STAGE = 0
|
||||
shaders northern-lights
|
||||
output_texture a
|
||||
endgroup
|
||||
|
||||
startgroup
|
||||
attach
|
||||
var int STAGE = 1
|
||||
shaders northern-lights
|
||||
output_texture persist
|
||||
endgroup
|
||||
|
||||
startgroup
|
||||
attach
|
||||
var int STAGE = 2
|
||||
shaders northern-lights
|
||||
endgroup
|
||||
@@ -0,0 +1,592 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Sami Farin
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
// Northern Lights — Volumetric Aurora Borealis - by Sami Farin
|
||||
//
|
||||
// Some ideas taken from a shader by gerardo-lcdf (MIT license):
|
||||
// https://godotshaders.com/shader/volumetric-aurora-borealis-with-polar-reflection/
|
||||
// The star field has been redesigned.
|
||||
//
|
||||
// Some important floats for tuning:
|
||||
// AURORA_INTENSITY - brightness of the aurora effect
|
||||
// ACCUMULATION_DECAY / MOUSE_PERSIST_INTENSITY - persistent trail on mouse click settings
|
||||
// STAR_BRIGHTNESS - set to 0.0f to disable star field
|
||||
// STAR_FIELD_ROTATIONS_SPEED - star field rotation speed
|
||||
// RESEED_INTERVAL - every RESEED_INTERVAL seconds the aurora is randomized again
|
||||
// DEBUG_MOUSE_OVERLAY - 1.0f enables debugging for mouse press location/effect
|
||||
// MARCH_STEPS - A value of 50 for highest quality and lower for greater speed
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
static const float PI = 3.14159265359f;
|
||||
static const float INITIAL_RANDOM_SEED = 0.12138f;
|
||||
|
||||
// === TERMINAL BLENDING CONTROLS ===
|
||||
static const float BLACK_BLEND_THRESHOLD = 0.15f;
|
||||
static const float EFFECT_INTENSITY = 0.25f;
|
||||
static const float TIME_SCALE = 0.25f;
|
||||
static const float EFFECT_FLOOR = 0.015f;
|
||||
static const float EFFECT_CEILING = 0.12f;
|
||||
|
||||
// === AURORA TUNING KNOBS ===
|
||||
static const float AURORA_INTENSITY = 0.2f;
|
||||
static const float AURORA_ALTITUDE = 0.6f;
|
||||
static const float AURORA_SCALE = 1.0f;
|
||||
static const float WAVE_SPEED = 0.55f;
|
||||
static const float MARCH_STEPS = 35.0f; // number of samples through the aurora, lower is faster but coarser
|
||||
static const float CURTAIN_SHARPNESS = 39.0f;
|
||||
static const float CURTAIN_SOFTNESS = 1.3f;
|
||||
static const float COLOR_VARIATION = 0.28f;
|
||||
static const float VERTICAL_FADE = 25.0f;
|
||||
static const float CAMERA_DISTANCE = 9.7f;
|
||||
static const float AURORA_DEPTH = 50.0f; // vertical extent of the aurora in units of the default march step
|
||||
|
||||
// === PERSISTENCE & DECAY CONTROLS ===
|
||||
static const float ACCUMULATION_DECAY = 0.03f; // Decay per frame: 0.0 = infinite, 0.005 = slow fade
|
||||
static const float MOUSE_PERSIST_INTENSITY = 1.1f; // Brightness multiplier for persistent rays
|
||||
|
||||
// === STAR FIELD CONTROLS ===
|
||||
static const float STAR_FIELD_ROTATIONS_SPEED = (2 * PI) / (86400 * TIME_SCALE);
|
||||
static const float STAR_BRIGHTNESS = 0.7f;
|
||||
static const float STAR_SIZE = 1.6f;
|
||||
static const float STAR_TWINKLE_SPEED = 0.05f;
|
||||
static const float STAR_DENSITY = 6.0f;
|
||||
static const float STAR_BRIGHTNESS_VARIATION = 6.0f;
|
||||
|
||||
// === TURBULENCE & CHROMATIC TWINKLE TUNING KNOBS ===
|
||||
static const float STAR_TURBULENCE_SCALE = 8.0f;
|
||||
static const float3 STAR_WIND_DRIFT_SPEED = float3(0.12f, 0.04f, 0.08f);
|
||||
static const float STAR_DISPERSION_SCALE = 0.06f;
|
||||
static const float STAR_DISPERSION_HORIZON_FACTOR = 1.2f;
|
||||
static const float3 STAR_DISPERSION_DIR = float3(0.3f, 0.8f, 0.2f);
|
||||
|
||||
static const float STAR_TWINKLE_BASE = 0.7f;
|
||||
static const float STAR_TWINKLE_AMPLITUDE = 0.2f;
|
||||
static const float STAR_TWINKLE_WAVE_B_MULT = 0.9f;
|
||||
static const float STAR_TWINKLE_WAVE_C_MULT = 2.3f;
|
||||
static const float STAR_TWINKLE_CORRELATION = 0.85f;
|
||||
|
||||
static const float3 TWINKLE_WAVE_DIR_A = float3(1.618f, 2.718f, 1.414f);
|
||||
static const float3 TWINKLE_WAVE_DIR_B = float3(2.414f, 1.732f, 3.141f);
|
||||
static const float3 TWINKLE_WAVE_DIR_C = float3(2.236f, 3.302f, 1.732f);
|
||||
|
||||
// === RANDOMIZATION CONTROLS ===
|
||||
static const float RANDOMIZE = 1.0f;
|
||||
static const float RESEED_INTERVAL = 300.0f;
|
||||
static const float TRANSITION_DIP = 2.5f;
|
||||
static const float DIP_LEVEL = 0.30f;
|
||||
|
||||
// === MOUSE TRAIL & RADIAL RAY SHAPE CONTROLS ===
|
||||
static const float MOUSE_AURORA_INTENSITY = 0.15f;
|
||||
static const float MOUSE_TRAIL_WIDTH = 0.06f;
|
||||
static const float MOUSE_RAY_WIDTH = 0.015f; // Tangential ray width
|
||||
static const float MOUSE_RAY_LENGTH = 0.11f; // Radial ray length along center alignment
|
||||
static const float MOUSE_RAY_FREQUENCY = 160.0f; // Fine curtain thread streaking frequency
|
||||
static const float MOUSE_TRAIL_NOISE_SCALE = 3.0f;
|
||||
static const float MOUSE_PRESS_BOOST = 0.3f;
|
||||
static const float MOUSE_IGNORE_WHEN_HIDDEN = 0.0f;
|
||||
static const float DEBUG_MOUSE_OVERLAY = 0.0f;
|
||||
|
||||
static const float3 SKY_COLOR_TOP = float3(0.05f, 0.1f, 0.2f);
|
||||
static const float3 SKY_COLOR_BOTTOM = float3(0.1f, 0.05f, 0.2f);
|
||||
|
||||
static const float2x2 TRI_ROT_MATRIX = float2x2(0.95534f, 0.29552f, -0.29552f, 0.95534f);
|
||||
|
||||
static const float LATITUDE_DEGREES = 61.2f;
|
||||
static const float LAT_RAD = LATITUDE_DEGREES * (3.14159265359f / 180.0f);
|
||||
static const float3 CELESTIAL_POLE = float3(0.0f, sin(LAT_RAD), cos(LAT_RAD));
|
||||
static const float PERSPECTIVE_TILT = 0.12f;
|
||||
|
||||
static const int STAR_LAYERS = 4;
|
||||
static const float STAR_LAYER_DENSITY[STAR_LAYERS] = { 0.0005f, 0.0015f, 0.0045f, 0.0125f };
|
||||
|
||||
static const float TWINKLE_FREQ_A = 1.618034f;
|
||||
static const float TWINKLE_FREQ_B = 2.414214f;
|
||||
|
||||
static const int STAGE = 0; // internal use only
|
||||
|
||||
// === TRIANGLE WAVE NOISE ===
|
||||
|
||||
float2x2
|
||||
rotation2d(float angle) {
|
||||
float c = cos(angle);
|
||||
float s = sin(angle);
|
||||
return float2x2(c, s, -s, c);
|
||||
}
|
||||
|
||||
float
|
||||
triWave(float x) {
|
||||
return clamp(abs(frac(x) - 0.5f), 0.01f, 0.49f);
|
||||
}
|
||||
|
||||
float2
|
||||
triWave2(float2 p) {
|
||||
return float2(triWave(p.x) + triWave(p.y), triWave(p.y + triWave(p.x)));
|
||||
}
|
||||
|
||||
// timeRot is the rotation by timestamp * speed, it is loop invariant so passed in by the caller
|
||||
float
|
||||
triNoise2d(float2 p, float2x2 timeRot, float sharpness) {
|
||||
float z = 1.8f;
|
||||
float z2 = 2.5f;
|
||||
float rz = 0.0f;
|
||||
|
||||
float c = cos(p.x * 0.06f);
|
||||
float s = sin(p.x * 0.06f);
|
||||
p = mul(float2x2(c, s, -s, c), p);
|
||||
|
||||
float2 bp = p;
|
||||
|
||||
[ForceUnroll]
|
||||
for (int i = 0; i < 5; i++) {
|
||||
float2 dg = mul(timeRot, triWave2(bp * 1.85f) * 0.75f);
|
||||
p -= dg / z2;
|
||||
|
||||
bp *= 1.3f;
|
||||
z2 *= 0.45f;
|
||||
z *= 0.42f;
|
||||
p *= 1.21f + (rz - 1.0f) * 0.02f;
|
||||
|
||||
rz += triWave(p.x + triWave(p.y)) * z;
|
||||
p = mul(TRI_ROT_MATRIX, p) * -1.0f;
|
||||
}
|
||||
|
||||
return clamp(1.0f / pow(rz * sharpness, CURTAIN_SOFTNESS), 0.0f, 0.55f);
|
||||
}
|
||||
|
||||
// === HASH FUNCTIONS ===
|
||||
|
||||
float
|
||||
hash21(float2 n) {
|
||||
return frac(sin(dot(n, float2(12.9898f, 4.1414f))) * 43758.5453f);
|
||||
}
|
||||
|
||||
uint
|
||||
pcgHash(uint v) {
|
||||
v = v * 747796405u + 2891336453u;
|
||||
uint w = ((v >> ((v >> 28u) + 4u)) ^ v) * 277803737u;
|
||||
return (w >> 22u) ^ w;
|
||||
}
|
||||
|
||||
float
|
||||
epochRand(uint epoch, uint channel) {
|
||||
uint seed = epoch * 0x9E3779B9u ^ (channel * 0x85EBCA6Bu + 0x27D4EB2Fu);
|
||||
return float(pcgHash(seed)) * (1.0f / 4294967295.0f);
|
||||
}
|
||||
|
||||
float3
|
||||
pcgHash33(float3 q) {
|
||||
const uint STREAM_X = 0x9E3779B9u;
|
||||
const uint STREAM_Y = 0x85EBCA6Bu;
|
||||
const uint STREAM_Z = 0xC2B2AE35u;
|
||||
|
||||
uint3 p = uint3(int3(floor(q)));
|
||||
|
||||
const uint MULT = 0x5851F42Du;
|
||||
|
||||
uint h = p.x * MULT + p.y * 0x27D4EB2Fu + p.z * 0x165667B1u + STREAM_X;
|
||||
h = ((h >> ((h >> 28u) + 4u)) ^ h) * 277803737u;
|
||||
uint outX = (h >> 22u) ^ h;
|
||||
|
||||
h = p.y * MULT + p.z * 0x27D4EB2Fu + p.x * 0x165667B1u + STREAM_Y;
|
||||
h = ((h >> ((h >> 28u) + 4u)) ^ h) * 277803737u;
|
||||
uint outY = (h >> 22u) ^ h;
|
||||
|
||||
h = p.z * MULT + p.x * 0x27D4EB2Fu + p.y * 0x165667B1u + STREAM_Z;
|
||||
h = ((h >> ((h >> 28u) + 4u)) ^ h) * 277803737u;
|
||||
uint outZ = (h >> 22u) ^ h;
|
||||
|
||||
return float3(outX, outY, outZ) * (1.0f / 4294967295.0f);
|
||||
}
|
||||
|
||||
// === PER-EPOCH RANDOM PARAMETERS ===
|
||||
|
||||
struct AuroraRandParams {
|
||||
float timeOffset;
|
||||
float2 startOffset;
|
||||
float waveSpeedMul;
|
||||
float scaleMul;
|
||||
float sharpMul;
|
||||
float colorJitter;
|
||||
float intensityMul;
|
||||
};
|
||||
|
||||
AuroraRandParams
|
||||
identityParams() {
|
||||
AuroraRandParams rp;
|
||||
rp.timeOffset = 0.0f;
|
||||
rp.startOffset = float2(0.0f, 0.0f);
|
||||
rp.waveSpeedMul = 1.0f;
|
||||
rp.scaleMul = 1.0f;
|
||||
rp.sharpMul = 1.0f;
|
||||
rp.colorJitter = 0.0f;
|
||||
rp.intensityMul = 1.0f;
|
||||
return rp;
|
||||
}
|
||||
|
||||
AuroraRandParams
|
||||
epochParams(uint epoch) {
|
||||
AuroraRandParams rp;
|
||||
rp.timeOffset = epochRand(epoch, 1u) * 4096.0f;
|
||||
rp.startOffset = float2(0.0f, 0.0f);
|
||||
rp.waveSpeedMul = lerp(0.75f, 1.25f, epochRand(epoch, 6u));
|
||||
rp.scaleMul = lerp(0.85f, 1.15f, epochRand(epoch, 7u));
|
||||
rp.sharpMul = lerp(0.80f, 1.20f, epochRand(epoch, 8u));
|
||||
rp.colorJitter = lerp(-0.6f, 0.6f, epochRand(epoch, 9u));
|
||||
rp.intensityMul = lerp(0.85f, 1.15f, epochRand(epoch, 10u));
|
||||
return rp;
|
||||
}
|
||||
|
||||
AuroraRandParams
|
||||
lerpParams(AuroraRandParams a, AuroraRandParams b, float t) {
|
||||
AuroraRandParams rp;
|
||||
rp.timeOffset = lerp(a.timeOffset, b.timeOffset, t);
|
||||
rp.startOffset = lerp(a.startOffset, b.startOffset, t);
|
||||
rp.waveSpeedMul = lerp(a.waveSpeedMul, b.waveSpeedMul, t);
|
||||
rp.scaleMul = lerp(a.scaleMul, b.scaleMul, t);
|
||||
rp.sharpMul = lerp(a.sharpMul, b.sharpMul, t);
|
||||
rp.colorJitter = lerp(a.colorJitter, b.colorJitter, t);
|
||||
rp.intensityMul = lerp(a.intensityMul, b.intensityMul, t);
|
||||
return rp;
|
||||
}
|
||||
|
||||
AuroraRandParams
|
||||
getAuroraParams(float rawTimestamp, float randomFloat) {
|
||||
if (RANDOMIZE <= 0.001f) return identityParams();
|
||||
uint launchOffset = uint(randomFloat * 100000.0f);
|
||||
uint epoch = uint(floor(rawTimestamp / RESEED_INTERVAL)) + launchOffset;
|
||||
return lerpParams(identityParams(), epochParams(epoch), RANDOMIZE);
|
||||
}
|
||||
|
||||
float
|
||||
transitionBrightness(float rawTimestamp) {
|
||||
if (RANDOMIZE <= 0.001f) return 1.0f;
|
||||
float ph = frac(rawTimestamp / RESEED_INTERVAL);
|
||||
float dEpoch = min(ph, 1.0f - ph) * RESEED_INTERVAL;
|
||||
float halfDip = TRANSITION_DIP * 0.5f;
|
||||
if (dEpoch >= halfDip) return 1.0f;
|
||||
float u = dEpoch / max(halfDip, 1e-4f);
|
||||
return lerp(DIP_LEVEL, 1.0f, smoothstep(0.0f, 1.0f, u));
|
||||
}
|
||||
|
||||
// === PROCEDURAL STARS ===
|
||||
|
||||
float
|
||||
magnitudeToBrightness(float hashVal) {
|
||||
float mag = hashVal * STAR_BRIGHTNESS_VARIATION;
|
||||
return pow(10.0f, -0.4f * mag);
|
||||
}
|
||||
|
||||
float
|
||||
evalTwinkleWave(float3 pos, float seed, float horizonFactor) {
|
||||
float variance = 1.0f - STAR_TWINKLE_CORRELATION;
|
||||
|
||||
float seedPhaseA = seed * 6.2831853f * variance;
|
||||
float seedPhaseB = seed * 3.14159265f * variance;
|
||||
float seedPhaseC = seed * 4.71238898f * variance;
|
||||
float freqMod = 1.0f + (frac(seed * 17.13f) - 0.5f) * 0.6f * variance;
|
||||
|
||||
float spd = STAR_TWINKLE_SPEED * freqMod * horizonFactor;
|
||||
|
||||
float waveA = sin(dot(pos, TWINKLE_WAVE_DIR_A) * spd + seedPhaseA);
|
||||
float waveB = cos(dot(pos, TWINKLE_WAVE_DIR_B) * spd * STAR_TWINKLE_WAVE_B_MULT + seedPhaseB + waveA * 0.7f);
|
||||
float waveC = sin(dot(pos, TWINKLE_WAVE_DIR_C) * spd * STAR_TWINKLE_WAVE_C_MULT + seedPhaseC);
|
||||
float microFlash = pow(clamp(waveC * 0.5f + 0.5f, 0.0f, 1.0f), 3.0f);
|
||||
|
||||
float combined = waveA * 0.45f + waveB * 0.35f + (microFlash - 0.2f) * 0.4f;
|
||||
|
||||
return max(0.0f, STAR_TWINKLE_BASE + STAR_TWINKLE_AMPLITUDE * combined * horizonFactor);
|
||||
}
|
||||
|
||||
float3
|
||||
continuousChromaticTwinkle(float3 rd, float time, float seed) {
|
||||
float3 turbulencePos = rd * STAR_TURBULENCE_SCALE;
|
||||
float3 windDrift = time * STAR_WIND_DRIFT_SPEED;
|
||||
float3 p = turbulencePos + windDrift;
|
||||
|
||||
float horizonFactor = 1.0f + 0.8f * saturate(STAR_DISPERSION_HORIZON_FACTOR - rd.y);
|
||||
float dispersionScale = STAR_DISPERSION_SCALE * saturate(STAR_DISPERSION_HORIZON_FACTOR - rd.y);
|
||||
|
||||
float3 pR = p - STAR_DISPERSION_DIR * dispersionScale;
|
||||
float3 pG = p;
|
||||
float3 pB = p + STAR_DISPERSION_DIR * dispersionScale;
|
||||
|
||||
float twR = evalTwinkleWave(pR, seed, horizonFactor);
|
||||
float twG = evalTwinkleWave(pG, seed, horizonFactor);
|
||||
float twB = evalTwinkleWave(pB, seed, horizonFactor);
|
||||
|
||||
return float3(twR, twG, twB);
|
||||
}
|
||||
|
||||
float3
|
||||
sampleStars(float3 rd, float2 res, float time) {
|
||||
if (STAR_BRIGHTNESS <= 0.0f) return float3(0.0f, 0.0f, 0.0f);
|
||||
|
||||
float rotSpeed = STAR_FIELD_ROTATIONS_SPEED;
|
||||
float angle = time * rotSpeed;
|
||||
float ca = cos(angle);
|
||||
float sa = sin(angle);
|
||||
|
||||
float3 rotRd = rd * ca + cross(CELESTIAL_POLE, rd) * sa + CELESTIAL_POLE * dot(CELESTIAL_POLE, rd) * (1.0f - ca);
|
||||
|
||||
float3 c = float3(0.0f, 0.0f, 0.0f);
|
||||
|
||||
[ForceUnroll]
|
||||
for (int i = 0; i < STAR_LAYERS; i++) {
|
||||
float scale = (0.15f + float(i) * 0.02f) * res.x;
|
||||
|
||||
float3 layerOffset = float3(float(i) * 0.371f, float(i) * 0.519f, float(i) * 0.163f);
|
||||
float3 scaledRd = rotRd * scale + layerOffset;
|
||||
|
||||
float3 q = frac(scaledRd) - 0.5f;
|
||||
float3 id = floor(scaledRd);
|
||||
float3 rn = pcgHash33(id);
|
||||
|
||||
float threshold = STAR_LAYER_DENSITY[i] * STAR_DENSITY;
|
||||
if (rn.x >= threshold) continue;
|
||||
|
||||
float c2 = 1.0f - smoothstep(0.0f, STAR_SIZE, length(q));
|
||||
float3 twinkleRGB = continuousChromaticTwinkle(rotRd, time, rn.y);
|
||||
float starFlux = magnitudeToBrightness(rn.y);
|
||||
float3 starCol = lerp(float3(1.0f, 0.49f, 0.1f), float3(0.75f, 0.9f, 1.0f), rn.z);
|
||||
|
||||
c += c2 * starCol * starFlux * twinkleRGB;
|
||||
}
|
||||
return c * c * STAR_BRIGHTNESS;
|
||||
}
|
||||
|
||||
// === MOUSE TRAIL FIELD ===
|
||||
|
||||
float
|
||||
mouseTrailField(float3 worldPos, float2 mouseWorld, float mouseValid, float strength) {
|
||||
if (strength <= 0.0f || mouseValid <= 0.5f) return 0.0f;
|
||||
|
||||
float dist = length(worldPos.xz - mouseWorld);
|
||||
|
||||
float falloff = saturate(1.0f - dist / MOUSE_TRAIL_WIDTH);
|
||||
falloff = falloff * falloff * (3.0f - 2.0f * falloff);
|
||||
|
||||
return falloff * strength;
|
||||
}
|
||||
|
||||
// === ZENITH PROJECTION HELPER ===
|
||||
|
||||
float3
|
||||
zenithRayDir(float2 centeredUV, float aspect, float horizonRadius, float spinCos, float spinSin) {
|
||||
float2 scaledUV = centeredUV * float2(aspect, 1.0f) * horizonRadius;
|
||||
float r2 = dot(scaledUV, scaledUV);
|
||||
float rd_y = 1.0f / sqrt(1.0f + r2);
|
||||
float3 rd = normalize(float3(scaledUV.x, rd_y, scaledUV.y));
|
||||
|
||||
float ct = cos(PERSPECTIVE_TILT);
|
||||
float st = sin(PERSPECTIVE_TILT);
|
||||
rd.yz = float2(rd.y * ct - rd.z * st, rd.y * st + rd.z * ct);
|
||||
|
||||
rd.xz = mul(float2x2(spinCos, spinSin, -spinSin, spinCos), rd.xz);
|
||||
return rd;
|
||||
}
|
||||
|
||||
// === VOLUMETRIC AURORA RAY MARCH ===
|
||||
|
||||
float4
|
||||
rayMarchAurora(
|
||||
float3 ro,
|
||||
float3 rd,
|
||||
float2 fragCoord,
|
||||
float noiseTime,
|
||||
AuroraRandParams rp,
|
||||
float2 mouseWorld,
|
||||
float mouseValid,
|
||||
float genStrength,
|
||||
float persistentTrail) {
|
||||
float stepCount = MARCH_STEPS;
|
||||
// Sample the same volume regardless of stepCount, with each sample standing in for stepScale slices
|
||||
float stepScale = AURORA_DEPTH / stepCount;
|
||||
|
||||
float effSpeed = WAVE_SPEED * rp.waveSpeedMul;
|
||||
float effSharpness = CURTAIN_SHARPNESS * rp.sharpMul;
|
||||
float effScale = AURORA_SCALE * rp.scaleMul;
|
||||
|
||||
float3 accColor = float3(0.0f);
|
||||
float accAlpha = 0.0f;
|
||||
|
||||
float2x2 densityRot = rotation2d(noiseTime * effSpeed);
|
||||
float2x2 trailRot = rotation2d(noiseTime * effSpeed * 1.5f);
|
||||
float jitter = 0.006f * hash21(fragCoord);
|
||||
|
||||
// Do not unroll this loop, doing so makes the shader too large to fit in the GPU instruction cache
|
||||
for (int i = 0; i < int(stepCount); i++) {
|
||||
float slice = float(i) * stepScale;
|
||||
|
||||
float of = jitter * smoothstep(0.0f, 15.0f, slice);
|
||||
float pt = ((AURORA_ALTITUDE + pow(slice, 1.4f) * 0.002f) - ro.y) / (rd.y * 2.0f + 0.4f);
|
||||
pt -= of;
|
||||
|
||||
if (pt < 0.0f) continue;
|
||||
|
||||
float3 bpos = ro + pt * rd;
|
||||
float2 p = bpos.zx * effScale + rp.startOffset;
|
||||
float density = triNoise2d(p, densityRot, effSharpness);
|
||||
|
||||
float trailField = mouseTrailField(bpos, mouseWorld, mouseValid, genStrength) + persistentTrail;
|
||||
// The trail noise is as expensive as the density noise, so only evaluate it where there is a trail
|
||||
if (trailField > 0.0f) {
|
||||
float trailNoise = triNoise2d(p * MOUSE_TRAIL_NOISE_SCALE + mouseWorld * 0.5f, trailRot, effSharpness * 0.8f);
|
||||
density = saturate(density + trailField * (trailNoise + 0.6f));
|
||||
}
|
||||
|
||||
float h = slice / AURORA_DEPTH;
|
||||
float3 colLow = float3(0.1f, 0.95f, 0.4f);
|
||||
float3 colMid = float3(0.1f, 0.85f, 0.85f);
|
||||
float3 colHigh = float3(0.65f, 0.25f, 0.95f);
|
||||
float t1 = smoothstep(0.0f, 0.45f, h);
|
||||
float t2 = smoothstep(0.35f, 1.0f, h);
|
||||
float3 baseCol = lerp(lerp(colLow, colMid, t1), colHigh, t2);
|
||||
baseCol += sin(float3(0.0f, 1.0f, 2.0f) + h * 6.0f + rp.colorJitter) * 0.06f;
|
||||
baseCol = max(baseCol, float3(0.0f));
|
||||
|
||||
float3 mouseCol = float3(0.15f, 0.75f, 1.0f);
|
||||
float3 stepColor = lerp(baseCol, mouseCol, saturate(trailField * 1.5f));
|
||||
|
||||
density *= stepScale;
|
||||
float absorption = exp(-accAlpha * 2.0f);
|
||||
accColor += stepColor * density * absorption;
|
||||
accAlpha += density * 0.05f;
|
||||
}
|
||||
|
||||
accColor *= AURORA_INTENSITY * rp.intensityMul;
|
||||
|
||||
return float4(accColor, saturate(accAlpha));
|
||||
}
|
||||
|
||||
// === SMOOTH CUTOFF ===
|
||||
|
||||
float
|
||||
smoothCutoff(float value, float floor_, float ceiling) {
|
||||
float t = saturate((value - floor_) / max(ceiling - floor_, 0.001f));
|
||||
return t * t * (3.0f - 2.0f * t);
|
||||
}
|
||||
|
||||
// === ENTRY POINT ===
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
float2 pixelDims = float2(d.viewport_size_pixels) * t.viewport.zw;
|
||||
float timestamp = d.wrapped_time(86400u) * TIME_SCALE;
|
||||
|
||||
float2 uv = t.pos;
|
||||
float aspect = pixelDims.x / max(pixelDims.y, 1.0f);
|
||||
|
||||
float2 mouseUV = (d.mouse_pos.xy - t.viewport.xy) / max(t.viewport.zw, float2(1e-5f, 1e-5f));
|
||||
bool inWindow = all(mouseUV >= float2(0.0f)) && all(mouseUV <= float2(1.0f));
|
||||
float mouseValid = float(inWindow);
|
||||
if (MOUSE_IGNORE_WHEN_HIDDEN > 0.5f && d.mouse_pointer_hidden > 0.5f) mouseValid = 0.0f;
|
||||
|
||||
// First group: Accumulate radial aurora rays cast from sky center into scratch texture 'a'
|
||||
if (STAGE == 0) {
|
||||
float prev = t.persist.Sample(uv).r;
|
||||
float decayed = prev * saturate(1.0f - ACCUMULATION_DECAY);
|
||||
|
||||
float deposit = 0.0f;
|
||||
if (mouseValid > 0.5f && d.mouse_button_pressed.x > 0.5f) {
|
||||
// Aspect-corrected UVs relative to screen center (0.5, 0.5)
|
||||
float2 cUV = (uv - 0.5f) * float2(aspect, 1.0f);
|
||||
float2 mUV = (mouseUV - 0.5f) * float2(aspect, 1.0f);
|
||||
|
||||
// Radial direction vector from sky center through the mouse click
|
||||
float mLen = length(mUV);
|
||||
float2 mDir = (mLen > 0.0001f) ? (mUV / mLen) : float2(0.0f, 1.0f);
|
||||
float2 mTangent = float2(-mDir.y, mDir.x); // Perpendicular to radial ray
|
||||
|
||||
// Difference vector from click point to current pixel
|
||||
float2 diff = cUV - mUV;
|
||||
|
||||
// Project onto radial (along) and tangential (across) axes
|
||||
float distAlongRay = dot(diff, mDir);
|
||||
float distAcrossRay = dot(diff, mTangent);
|
||||
|
||||
// Asymmetric ray length extending outward from the click point
|
||||
float yMax = (distAlongRay >= 0.0f) ? MOUSE_RAY_LENGTH : (MOUSE_RAY_LENGTH * 0.25f);
|
||||
|
||||
float hDist = abs(distAcrossRay) / max(MOUSE_RAY_WIDTH, 0.001f);
|
||||
float vDist = abs(distAlongRay) / max(yMax, 0.001f);
|
||||
|
||||
// High-frequency curtain thread streaking along the ray width
|
||||
float streaks1 = sin(distAcrossRay * MOUSE_RAY_FREQUENCY) * 0.35f + 0.65f;
|
||||
float streaks2 = cos(distAcrossRay * MOUSE_RAY_FREQUENCY * 2.3f) * 0.25f + 0.75f;
|
||||
|
||||
float hFalloff = smoothstep(1.0f, 0.0f, hDist);
|
||||
float vFalloff = smoothstep(1.0f, 0.0f, vDist);
|
||||
|
||||
deposit = hFalloff * vFalloff * streaks1 * streaks2 * MOUSE_PRESS_BOOST;
|
||||
}
|
||||
|
||||
return float4(saturate(decayed + deposit), 0.0f, 0.0f, 1.0f);
|
||||
}
|
||||
|
||||
// Second group: Copy scratch texture 'a' to 'persist'
|
||||
if (STAGE == 1) { return t.a.Sample(uv); }
|
||||
|
||||
// Third group: Main composite pass
|
||||
AuroraRandParams rp = getAuroraParams(d.timestamp, INITIAL_RANDOM_SEED);
|
||||
float epochBrightness = transitionBrightness(d.timestamp);
|
||||
float noiseTime = timestamp + rp.timeOffset;
|
||||
|
||||
float2 fragCoord = uv * pixelDims;
|
||||
|
||||
float persistentTrail = t.persist.Sample(uv).r * MOUSE_PERSIST_INTENSITY;
|
||||
|
||||
float3 ro = float3(0.0f, 0.0f, -CAMERA_DISTANCE);
|
||||
float2 centeredUV = uv - 0.5f;
|
||||
|
||||
float horizonRadius = 1.5f;
|
||||
|
||||
float spinAngle = timestamp * 0.02f;
|
||||
float cs = cos(spinAngle), ss = sin(spinAngle);
|
||||
|
||||
float3 rd = zenithRayDir(centeredUV, aspect, horizonRadius, cs, ss);
|
||||
|
||||
float3 bgCol = lerp(SKY_COLOR_TOP, SKY_COLOR_BOTTOM, 1.0f - rd.y) * 0.63f;
|
||||
float3 col = bgCol;
|
||||
|
||||
float2 mouseWorld = float2(0.0f, 0.0f);
|
||||
|
||||
if (mouseValid > 0.5f) {
|
||||
float2 mCenteredUV = mouseUV - 0.5f;
|
||||
float3 mrd = zenithRayDir(mCenteredUV, aspect, horizonRadius, cs, ss);
|
||||
|
||||
float denom = mrd.y * 2.0f + 0.4f;
|
||||
if (denom > 0.001f) {
|
||||
float dist = (AURORA_ALTITUDE - ro.y) / denom;
|
||||
mouseWorld = (ro + mrd * dist).xz;
|
||||
}
|
||||
}
|
||||
|
||||
float genStrength = MOUSE_AURORA_INTENSITY * (1.0f + d.mouse_button_pressed.x * MOUSE_PRESS_BOOST);
|
||||
|
||||
float4 aur = smoothstep(0.0f, 1.5f, rayMarchAurora(ro, rd, fragCoord, noiseTime, rp, mouseWorld, mouseValid, genStrength, persistentTrail));
|
||||
col += sampleStars(rd, pixelDims, timestamp);
|
||||
col = col * (1.0f - aur.a) + aur.rgb;
|
||||
|
||||
col *= EFFECT_INTENSITY * epochBrightness;
|
||||
|
||||
float effectLum = dot(col, float3(0.299f, 0.587f, 0.114f));
|
||||
float gate = smoothCutoff(effectLum, EFFECT_FLOOR, EFFECT_CEILING);
|
||||
col *= gate;
|
||||
|
||||
float4 terminalColor = t.backbuffer.Sample(uv);
|
||||
float termLum = dot(terminalColor.rgb, float3(0.299f, 0.587f, 0.114f));
|
||||
float isBlack = step(termLum, 0.001f);
|
||||
float textPreserve = 1.0f - smoothstep(BLACK_BLEND_THRESHOLD, BLACK_BLEND_THRESHOLD + 0.2f, termLum);
|
||||
float blendFactor = lerp(textPreserve * EFFECT_INTENSITY, 1.0f, isBlack);
|
||||
float3 blendedColor = terminalColor.rgb + col * blendFactor;
|
||||
|
||||
if (DEBUG_MOUSE_OVERLAY > 0.5f && mouseValid > 0.5f) {
|
||||
float ptProxy = (AURORA_ALTITUDE - ro.y) / (rd.y * 2.0f + 0.4f);
|
||||
float g = mouseTrailField(ro + rd * ptProxy, mouseWorld, 1.0f, genStrength);
|
||||
blendedColor = lerp(blendedColor, float3(1.0f, 0.25f, 0.05f), saturate(g * 2.0f));
|
||||
}
|
||||
|
||||
return float4(blendedColor, terminalColor.a);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
// IMPORTS
|
||||
|
||||
public struct BlitOutput {
|
||||
float2 texcoord;
|
||||
float2 position;
|
||||
};
|
||||
|
||||
#define left 0
|
||||
#define top 1
|
||||
#define right 2
|
||||
#define bottom 3
|
||||
|
||||
// Static constant array mapping vertex IDs
|
||||
static const int2 vertex_pos_map[4] = { { right, top }, { right, bottom }, { left, bottom }, { left, top } };
|
||||
|
||||
BlitOutput
|
||||
get_coords_for_blit(uint vertex_id, float4 src_rect, float4 dest_rect) {
|
||||
int2 pos = vertex_pos_map[vertex_id];
|
||||
BlitOutput output;
|
||||
output.texcoord = float2(src_rect[pos.x], src_rect[pos.y]);
|
||||
output.position = float2(dest_rect[pos.x], dest_rect[pos.y]);
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
public ConstantBuffer<KittyCustomShaderData> csd;
|
||||
|
||||
|
||||
public float4
|
||||
pipeline_vertex_main(uint vertex_id) {
|
||||
BlitOutput ans = get_coords_for_blit(vertex_id, csd.src_rect, csd.dest_rect);
|
||||
return float4(ans.texcoord[0], ans.texcoord[1], ans.position[0], ans.position[1]);
|
||||
}
|
||||
|
||||
float4
|
||||
vec4_premul(float3 rgb, float a) {
|
||||
return float4(rgb * a, a);
|
||||
}
|
||||
|
||||
float
|
||||
linear2srgb(float x) { // scalar
|
||||
float lower = 12.92 * x;
|
||||
float upper = 1.055 * pow(x, 1.0f / 2.4f) - 0.055f;
|
||||
|
||||
return lerp(lower, upper, step(0.0031308f, x));
|
||||
}
|
||||
|
||||
float3
|
||||
linear2srgb(float3 x) { // vector
|
||||
float3 lower = 12.92 * x;
|
||||
float3 upper = 1.055 * pow(x, float3(1.0f / 2.4f)) - 0.055f;
|
||||
|
||||
return lerp(lower, upper, step(float3(0.0031308f), x));
|
||||
}
|
||||
|
||||
uniform Sampler2D backbuffer, a, b, persist;
|
||||
|
||||
// The size of the pointer map grid, POINTER_MAP_SIZE is defined by kitty from state.h when compiling
|
||||
static const float pointer_map_size = POINTER_MAP_SIZE;
|
||||
|
||||
// Where the content visible at pos actually is, as decided by the pointer_map()
|
||||
// functions of the shaders that move content around. Shaders in groups that
|
||||
// are turned on and off by events apply only when the bit for their group is
|
||||
// set in active_groups.
|
||||
float2
|
||||
pipeline_pointer_map(float2 pos, uint active_groups) {
|
||||
// POINTER_MAP
|
||||
return pos;
|
||||
}
|
||||
|
||||
// Rendered when group is negative, to compute the pointer map. Each coordinate
|
||||
// is split over two 8 bit channels so that it is precise even on GPU drivers
|
||||
// that cannot render to 16 bit textures.
|
||||
float4
|
||||
encode_pointer_map(float2 texel_pos, uint active_groups) {
|
||||
// Spread the texels so that the first and last ones land exactly on the edges
|
||||
float2 pos = (texel_pos * pointer_map_size - 0.5f) / (pointer_map_size - 1.f);
|
||||
float2 q = round(saturate(pipeline_pointer_map(pos, active_groups)) * 65535.f);
|
||||
float2 hi = floor(q / 256.f);
|
||||
return float4(hi / 255.f, (q - hi * 256.f) / 255.f);
|
||||
}
|
||||
|
||||
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;
|
||||
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.
|
||||
float2 max_pos = 1.f - 0.5f / max(float2(csd.viewport_size_pixels), float2(1.f));
|
||||
KittyTextures t = {
|
||||
{ backbuffer, src_scale, max_pos },
|
||||
{ a, src_scale, max_pos },
|
||||
{ b, src_scale, max_pos },
|
||||
{ persist, src_scale, max_pos },
|
||||
viewport_pos,
|
||||
viewport,
|
||||
animation_progress,
|
||||
group
|
||||
};
|
||||
// PIPELINE
|
||||
return vec4_premul(color.rgb, color.a);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
startgroup
|
||||
animation_start pointer-left-button-press
|
||||
animation_stop 1500
|
||||
animation_curve linear
|
||||
animation_step 16
|
||||
shaders pond-ripple
|
||||
endgroup
|
||||
@@ -0,0 +1,91 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Pond ripple effect — concentric expanding rings centered on pointer-left-button-press.
|
||||
// animation_progress (0 → 1) drives the wavefront expansion over the pipeline duration.
|
||||
// 3D lighting via analytic surface normals and Blinn-Phong specular highlights.
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
// Maximum wavefront radius at animation_progress=1 (aspect-corrected UV units).
|
||||
static const float WAVE_SPEED = 0.45;
|
||||
// Spatial frequency of the rings (cycles per aspect-corrected UV unit).
|
||||
static const float WAVE_FREQUENCY = 14.0;
|
||||
// Starting half-width of the Gaussian envelope (expands as animation_progress increases).
|
||||
static const float WAVE_WIDTH = 0.055;
|
||||
// Peak radial UV displacement at the wavecrest.
|
||||
static const float AMPLITUDE = 0.010;
|
||||
// Scale applied to the wave gradient when constructing the surface normal.
|
||||
static const float NORMAL_SCALE = 8.0;
|
||||
// Blinn-Phong shininess exponent — higher values give a sharper, more mirror-like glint.
|
||||
static const float SHININESS = 64.0;
|
||||
// Peak specular contribution at the wave crest facing the light.
|
||||
static const float SPECULAR_STRENGTH = 0.40;
|
||||
// Subtle diffuse shading that rounds each ring into a 3D ridge.
|
||||
static const float DIFFUSE_STRENGTH = 0.10;
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
float2 pixelDims = float2(d.viewport_size_pixels) * t.viewport.zw;
|
||||
float aspect = pixelDims.x / pixelDims.y;
|
||||
|
||||
// d.mouse_pos.zw is the UV position of the last left-button press (y=0 at bottom).
|
||||
float2 center = d.mouse_pos.zw;
|
||||
|
||||
// Aspect-corrected vector from the click center to this pixel.
|
||||
float2 delta = (t.pos - center) * float2(aspect, 1.0);
|
||||
float dist = length(delta);
|
||||
float2 dir = delta / max(dist, 1e-5);
|
||||
|
||||
// Wavefront radius advances linearly with animation_progress.
|
||||
float front = WAVE_SPEED * t.animation_progress;
|
||||
|
||||
// Signed distance from the wavefront (negative = wave has passed, positive = not yet reached).
|
||||
float behind = dist - front;
|
||||
|
||||
// Gaussian spatial envelope centered at the wavefront; grows in width over time.
|
||||
float sigma = WAVE_WIDTH * (1.0 + t.animation_progress);
|
||||
float env = exp(-behind * behind / (2.0 * sigma * sigma));
|
||||
|
||||
// Causality: suppress any energy ahead of the wavefront.
|
||||
env *= 1.0 - smoothstep(-0.01, 0.02, behind);
|
||||
|
||||
// Temporal amplitude decay as the wave expands outward.
|
||||
float decay = pow(1.0 - t.animation_progress, 0.7);
|
||||
|
||||
float k = WAVE_FREQUENCY * 6.28318530718;
|
||||
float wave = sin(behind * k);
|
||||
|
||||
// Analytic derivative of wave height h = wave * env * decay w.r.t. dist.
|
||||
// d(wave)/d(behind) = k*cos(k*behind); d(env)/d(behind) = -behind/sigma^2 * env.
|
||||
float dh_ddist = (k * cos(behind * k) - wave * behind / (sigma * sigma)) * env * decay;
|
||||
|
||||
// Surface gradient in aspect-corrected UV space; dir is the unit radial vector.
|
||||
float2 grad = dh_ddist * dir;
|
||||
|
||||
// Surface normal: xy from negated gradient (slope), z pointing out of the screen.
|
||||
float3 N = normalize(float3(-grad * AMPLITUDE * NORMAL_SCALE, 1.0));
|
||||
|
||||
// Directional light from upper-right in screen space (y points up in UV, z out of screen).
|
||||
float3 L = normalize(float3(0.5, 0.7, 1.0));
|
||||
// Viewer looks straight into the screen.
|
||||
float3 V = float3(0.0, 0.0, 1.0);
|
||||
// Blinn-Phong half-vector.
|
||||
float3 H = normalize(L + V);
|
||||
|
||||
float diffuse = max(dot(N, L), 0.0);
|
||||
float specular = pow(max(dot(N, H), 0.0), SHININESS);
|
||||
|
||||
// Radial UV displacement: push pixels away from center at crests, pull inward at troughs.
|
||||
float2 warpedUV = clamp(t.pos + dir * (wave * env * decay * AMPLITUDE), float2(0.0), float2(1.0));
|
||||
|
||||
// Sample the terminal backbuffer at the displaced position.
|
||||
float4 result = t.backbuffer.Sample(warpedUV);
|
||||
|
||||
// 3D lighting: diffuse rounds each ring into a ridge, specular gives directional glints.
|
||||
float lighting = 1.0 + diffuse * DIFFUSE_STRENGTH * env * decay + specular * SPECULAR_STRENGTH * env * decay;
|
||||
result.rgb *= lighting;
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
static const float FACTOR = 2;
|
||||
|
||||
// START_FUNCTION_SIGNATURE
|
||||
public float4
|
||||
fragment_main(
|
||||
// The color from the previous custom shader in this group or from the
|
||||
// backbuffer if this is the first shader in the group
|
||||
float4 color,
|
||||
|
||||
// See types.slang for details on the data in this structure
|
||||
KittyTextures t,
|
||||
|
||||
// See types.slang for details on the data in this structure
|
||||
KittyCustomShaderData d) {
|
||||
// END_FUNCTION_SIGNATURE
|
||||
return float4(color.r, min(max(0.1, color.g) * FACTOR, 1), color.b, color.a);
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
startgroup
|
||||
animation_start os-window-focus-in | user-activity
|
||||
animation_stop os-window-focus-out | user-idle
|
||||
shaders spotlight
|
||||
endgroup
|
||||
@@ -0,0 +1,61 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Spotlight effect
|
||||
// Original GLSL by Paul Robello, ported to Slang for kitty
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
static const float SPOTLIGHT_RADIUS = 0.25; // spotlight radius in UV units
|
||||
static const float SPOTLIGHT_SOFTNESS = 20.0; // edge sharpness; higher = sharper
|
||||
static const float AMBIENT_LIGHT = 0.5; // minimum brightness outside the spotlight
|
||||
static const float SPOTLIGHT_SPEED = 1.0; // oscillation speed in random-motion mode
|
||||
// Set to 1 to follow the mouse, 0 to use random oscillation
|
||||
static const int USE_MOUSE = 1;
|
||||
// When USE_MOUSE=1 and the mouse leaves the window:
|
||||
// 0 = fall back to random oscillation
|
||||
// 1 = clamp spotlight to the nearest window edge
|
||||
// 2 = disable spotlight (pass through unchanged pixels)
|
||||
static const int MOUSE_LEAVE_BEHAVIOR = 2;
|
||||
// Set to 1 to pass through unchanged pixels when the mouse pointer is hidden
|
||||
static const int HIDE_WHEN_POINTER_HIDDEN = 1;
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
if (HIDE_WHEN_POINTER_HIDDEN == 1 && d.mouse_pointer_hidden != 0.0) return color;
|
||||
float2 uv = t.pos;
|
||||
|
||||
// Viewport pixel dimensions for aspect-ratio correction
|
||||
float2 pixelDims = float2(d.viewport_size_pixels) * t.viewport.zw;
|
||||
float aspectRatio = pixelDims.x / pixelDims.y;
|
||||
|
||||
// Random oscillating center (different frequencies and phases on each axis)
|
||||
float time = d.wrapped_time(3600u) * SPOTLIGHT_SPEED;
|
||||
float2 randomCenter = float2(0.5 + 0.4 * sin(time), 0.5 + 0.4 * sin(time * 1.3 + 3.14159));
|
||||
|
||||
// Mouse is valid only when both coords are inside the OS window [0, 1]
|
||||
float2 mp = d.mouse_pos.xy;
|
||||
float mouseInWindow = float(all(mp >= float2(0.0)) && all(mp <= float2(1.0)));
|
||||
|
||||
// Disable spotlight entirely when mouse leaves the window
|
||||
if (USE_MOUSE == 1 && MOUSE_LEAVE_BEHAVIOR == 2 && mouseInWindow == 0.0) return color;
|
||||
|
||||
// When mouse leaves the window: clamp to nearest edge or fall back to random
|
||||
float2 outsideFallback = lerp(randomCenter, clamp(mp, float2(0.0), float2(1.0)), float(MOUSE_LEAVE_BEHAVIOR == 1 ? 1 : 0));
|
||||
|
||||
// Branchless center selection
|
||||
float2 mouseCenter = lerp(outsideFallback, mp, mouseInWindow);
|
||||
float2 spotlightCenter = lerp(randomCenter, mouseCenter, float(USE_MOUSE));
|
||||
|
||||
// Euclidean distance in aspect-ratio-corrected space (produces a circular spotlight)
|
||||
float distToCenter = length((uv - spotlightCenter) * float2(aspectRatio, 1.0));
|
||||
|
||||
// Soft spotlight edge
|
||||
float spotlightIntensity = smoothstep(SPOTLIGHT_RADIUS, SPOTLIGHT_RADIUS - (1.0 / SPOTLIGHT_SOFTNESS), distToCenter);
|
||||
|
||||
// Blend between ambient and full illumination
|
||||
float3 result = color.rgb * lerp(float3(AMBIENT_LIGHT), float3(1.0), spotlightIntensity);
|
||||
|
||||
return float4(result, color.a);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
startgroup
|
||||
animation_start tab-change
|
||||
animation_stop 600
|
||||
animation_curve ease-out
|
||||
animation_step 16
|
||||
shaders tab-change
|
||||
endgroup
|
||||
@@ -0,0 +1,92 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Tab-change reveal shader
|
||||
// Plays a brief reveal animation whenever the active tab changes.
|
||||
// The reveal direction for wipe-based modes is derived from d.central_area:
|
||||
// the wipe starts at whichever edge of the content area is furthest from the
|
||||
// viewport boundary — that edge is where the tab bar sits.
|
||||
//
|
||||
// ANIMATION_TYPE selects the effect:
|
||||
// 0 = FADE — uniform brightness fade-in over the whole screen
|
||||
// 1 = WIPE — a single swept edge travelling away from the tab bar
|
||||
// 2 = BLINDS — sequential strip reveals sweeping away from the tab bar
|
||||
// 3 = IRIS — circular iris expanding from the centre of the content area
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
// 0=FADE, 1=WIPE, 2=BLINDS, 3=IRIS
|
||||
static const int ANIMATION_TYPE = 1;
|
||||
|
||||
// Number of strips for ANIMATION_TYPE == 2 (BLINDS).
|
||||
static const int NUM_BLINDS = 8;
|
||||
|
||||
// Soft-edge width in UV units used by WIPE and IRIS.
|
||||
static const float EDGE_SOFTNESS = 0.04;
|
||||
|
||||
// Returns a value in [0, 1] for this pixel: 0 at the tab-bar edge of the
|
||||
// content area, 1 at the opposite edge. The wipe sweeps from 0 toward 1.
|
||||
float
|
||||
wipe_pixel_pos(float2 uv, float4 ca) {
|
||||
float gap_left = ca.x;
|
||||
float gap_right = 1.0 - (ca.x + ca.z);
|
||||
float gap_bottom = ca.y;
|
||||
float gap_top = 1.0 - (ca.y + ca.w);
|
||||
float max_gap = max(max(gap_left, gap_right), max(gap_bottom, gap_top));
|
||||
|
||||
float pos;
|
||||
if (max_gap == gap_top) {
|
||||
// Tab bar at top — sweep from top-of-content downward
|
||||
pos = (ca.y + ca.w - uv.y) / ca.w;
|
||||
} else if (max_gap == gap_bottom) {
|
||||
// Tab bar at bottom — sweep from bottom-of-content upward
|
||||
pos = (uv.y - ca.y) / ca.w;
|
||||
} else if (max_gap == gap_left) {
|
||||
// Tab bar at left — sweep from left-of-content rightward
|
||||
pos = (uv.x - ca.x) / ca.z;
|
||||
} else {
|
||||
// Tab bar at right — sweep from right-of-content leftward
|
||||
pos = (ca.x + ca.z - uv.x) / ca.z;
|
||||
}
|
||||
return clamp(pos, 0.0, 1.0);
|
||||
}
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
float4 ca = d.central_area;
|
||||
if (ca.z <= 0.0 || ca.w <= 0.0) return color;
|
||||
|
||||
float p = t.animation_progress;
|
||||
float brightness;
|
||||
|
||||
if (ANIMATION_TYPE == 0) {
|
||||
// FADE: uniform ramp over the whole frame
|
||||
brightness = p;
|
||||
} else if (ANIMATION_TYPE == 1) {
|
||||
// WIPE: single swept edge with soft falloff
|
||||
float pixel_pos = wipe_pixel_pos(t.pos, ca);
|
||||
// 1.0 where revealed (pixel_pos < p), 0.0 where not yet reached
|
||||
brightness = 1.0 - smoothstep(p - EDGE_SOFTNESS, p + EDGE_SOFTNESS, pixel_pos);
|
||||
} else if (ANIMATION_TYPE == 2) {
|
||||
// BLINDS: strips opening in sequence from the tab-bar side
|
||||
float pixel_pos = wipe_pixel_pos(t.pos, ca);
|
||||
float inv_n = 1.0 / float(NUM_BLINDS);
|
||||
float strip_idx = floor(pixel_pos * float(NUM_BLINDS));
|
||||
float strip_start = strip_idx * inv_n;
|
||||
// Progress local to this strip: 0 when it starts opening, 1 when fully open
|
||||
float strip_p = clamp((p - strip_start) / inv_n, 0.0, 1.0);
|
||||
// Position within the strip (0 at tab-bar side, 1 at far side)
|
||||
float local = fract(pixel_pos * float(NUM_BLINDS));
|
||||
float soft = 0.1;
|
||||
brightness = 1.0 - smoothstep(strip_p - soft, strip_p + soft, local);
|
||||
} else {
|
||||
// IRIS: circular reveal expanding from the centre of the content area
|
||||
float2 ca_center = ca.xy + ca.zw * 0.5;
|
||||
float half_diag = length(ca.zw * 0.5);
|
||||
float dist = length(t.pos - ca_center) / max(half_diag, 0.001);
|
||||
brightness = 1.0 - smoothstep(p - EDGE_SOFTNESS, p + EDGE_SOFTNESS, dist);
|
||||
}
|
||||
|
||||
return float4(color.rgb * brightness, color.a);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Gives a pixelated appearance similar to early Thin Film Transistor LCD displays
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
// size of the simulated pixels
|
||||
static const float RESOLUTION = 4.0;
|
||||
|
||||
// strength of the effect
|
||||
static const float STRENGTH = 0.5;
|
||||
|
||||
void
|
||||
scanline(inout float3 color, float2 pixel_pos) {
|
||||
float scanline = step(1.2, fmod(pixel_pos.y, RESOLUTION));
|
||||
float grille = step(1.2, fmod(pixel_pos.x, RESOLUTION));
|
||||
color *= max(1.0 - STRENGTH, scanline * grille);
|
||||
}
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
float2 pixel_pos = t.pos * float2(d.viewport_size_pixels);
|
||||
float3 c = color.rgb;
|
||||
scanline(c, pixel_pos);
|
||||
return float4(c, 1.0);
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
|
||||
public struct KittyCustomShaderData {
|
||||
public float4 src_rect, dest_rect; // used by the vertex shader internally
|
||||
|
||||
// global background/foreground colors from kitty options (linear RGB, alpha=1)
|
||||
public float4 background, foreground;
|
||||
// background color of the active window in the active tab (linear RGB, alpha=1)
|
||||
public float4 active_window_background;
|
||||
// Mouse position in UV coordinates (origin at lower-left).
|
||||
// Values outside [0, 1] indicate the mouse is outside the OS window.
|
||||
// The first two co-ordinates are current position, the last two the
|
||||
// position of the last left mouse press.
|
||||
public float4 mouse_pos;
|
||||
// Press state of the first four mouse buttons (left, right, middle, button4).
|
||||
// Each component is 1.0 if the button is currently held, 0.0 otherwise.
|
||||
public float4 mouse_button_pressed;
|
||||
// Geometry of the currently active window in UV co-ordinates (origin bottom-left).
|
||||
// .xy = lower-left corner of the window, .zw = width and height.
|
||||
// All components are zero when no active window was rendered this frame.
|
||||
public float4 active_window_geometry;
|
||||
// Extents beyond the active content, including a visible title bar, margin,
|
||||
// border, padding and cell-size compensation.
|
||||
// .xy = left/bottom, .zw = right/top, in viewport UV units.
|
||||
public float4 active_window_padding;
|
||||
// Geometry of the most recently belled window in UV co-ordinates (origin bottom-left).
|
||||
// .xy = lower-left corner of the window, .zw = width and height.
|
||||
// If the belled window is not currently visible in the active tab/layout, equals central_area.
|
||||
// All components are zero until the first bell-in-window event occurs.
|
||||
public float4 bell_window_geometry;
|
||||
// Geometry of the central content area of the OS window (the tab area, excluding any tab bar)
|
||||
// in UV co-ordinates (origin bottom-left).
|
||||
// .xy = lower-left corner, .zw = width and height.
|
||||
// Equals the full viewport when no tab bar is visible.
|
||||
public float4 central_area;
|
||||
|
||||
// Cursor trail state (UV coordinates, origin bottom-left, (1,1) top-right).
|
||||
// All fields are zero when the cursor_trail kitty option is disabled or the trail is inactive.
|
||||
// The trail is a morphing quadrilateral whose four corners animate toward the cursor position.
|
||||
// Corner order: 0=top-right, 1=bottom-right, 2=bottom-left, 3=top-left.
|
||||
// Use animation_start cursor-trail-move / animation_stop cursor-trail-stop to activate.
|
||||
// animation_progress is NOT tied to trail duration; use cursor_trail_state.x for opacity instead.
|
||||
public float4 cursor_trail_corners_x; // UV x-coordinates of the 4 animated trail quad corners
|
||||
public float4 cursor_trail_corners_y; // UV y-coordinates of the 4 animated trail quad corners
|
||||
// Previous-frame animated trail quad corners. These are available for
|
||||
// custom shaders that perform temporal effects.
|
||||
public float4 cursor_trail_prev_corners_x;
|
||||
public float4 cursor_trail_prev_corners_y;
|
||||
// .x=left, .y=right, .z=top, .w=bottom UV edges of the current cursor rectangle
|
||||
public float4 cursor_trail_edge;
|
||||
// .x=left, .y=right, .z=top, .w=bottom UV edges of the cursor rectangle before the most recent move.
|
||||
// All zeros until the cursor has moved at least twice (first move establishes current; second move sets this).
|
||||
public float4 cursor_trail_prev_edge;
|
||||
// Effective cursor color (linear RGB) and opacity for the active window.
|
||||
// .rgb = cursor background color, .a = cursor opacity (0..1).
|
||||
// Both are zero when no active window was rendered this frame.
|
||||
public float4 cursor_color;
|
||||
// Effective cursor trail color (linear RGB) and opacity.
|
||||
// .rgb = trail color (falls back to cursor_color.rgb when cursor_trail_color option is "none").
|
||||
// .a = trail opacity (0..1); zero when the trail is inactive.
|
||||
public float4 cursor_trail_color;
|
||||
// The most recent cursor moves that started a cursor trail, most recent
|
||||
// first. Unlike the other cursor_trail_* fields these remain valid after
|
||||
// the trail has finished, so effects started by a move can outlive the
|
||||
// trail and effects from several moves can overlap.
|
||||
// .x=left, .y=right, .z=top, .w=bottom UV edges of the cursor rectangle
|
||||
// before (from) and after (to) the move.
|
||||
public float4 cursor_trail_history_from[8];
|
||||
public float4 cursor_trail_history_to[8];
|
||||
// Seconds since each move, move i is in cursor_trail_history_age[i / 4][i % 4].
|
||||
// Negative for unused entries.
|
||||
public float4 cursor_trail_history_age[2];
|
||||
// the size in pixels of the full underlying viewport we are rendering too,
|
||||
// before applying any viewport transforms from the current group.
|
||||
// You can use t.viewport to derive the actual size and position of the
|
||||
// viewport currently being rendered too.
|
||||
public uint2 viewport_size_pixels;
|
||||
|
||||
public float mouse_pointer_hidden; // 1.0 if the mouse pointer is currently hidden, 0.0 if visible
|
||||
public float cursor_trail_state; // 1.0 if the cursor trail is actively animating, 0.0 otherwise
|
||||
|
||||
// Time in seconds since kitty was started. Note that this loses precision
|
||||
// the longer kitty runs: it is accurate to 1ms only for the first ~4.7 hours
|
||||
// and to ~64ms after a week. So for animations use wrapped_time() below,
|
||||
// and for the time elapsed since an event, use the various *_age fields.
|
||||
public float timestamp;
|
||||
public float last_rendered_at; // time of previous render, same epoch and precision as timestamp
|
||||
public uint frame_counter; // cumulative frame counter increments by one every time a frame is fully rendered, first frame is zero
|
||||
// Time (same epoch and precision as `timestamp`) of the most recent cursor position change that triggered a trail.
|
||||
// Zero until the cursor has moved at least twice. Pair with cursor_trail_prev_edge.
|
||||
// Use cursor_trail_age instead to find how long ago this was.
|
||||
public float cursor_trail_change_time;
|
||||
|
||||
// timestamp split into whole seconds and the fraction of the current
|
||||
// second, which together are exact however long kitty runs. Usually you
|
||||
// want to use wrapped_time() below instead of these.
|
||||
public uint timestamp_seconds;
|
||||
public float timestamp_fraction; // in [0, 1)
|
||||
// Seconds between the previous render and this one, zero for the first render.
|
||||
public float time_since_last_render;
|
||||
// Seconds since cursor_trail_change_time, negative when cursor_trail_change_time is zero.
|
||||
public float cursor_trail_age;
|
||||
|
||||
// Seconds since kitty was started, wrapped to [0, period_seconds). Unlike
|
||||
// timestamp, this keeps sub-millisecond precision however long kitty runs,
|
||||
// as long as period_seconds is at most an hour or so. The value jumps back
|
||||
// to zero once every period, so either use a period over which your
|
||||
// animation repeats seamlessly, or a long one so that the jump is rare.
|
||||
public float
|
||||
wrapped_time(uint period_seconds) {
|
||||
return float(timestamp_seconds % period_seconds) + timestamp_fraction;
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
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.
|
||||
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.
|
||||
public float2 max_pos;
|
||||
|
||||
// Sample this texture at pos, which is in the same UV co-ordinate space as
|
||||
// KittyTextures.pos, that is, [0, 1] with the origin at the bottom-left.
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
public struct KittyTextures {
|
||||
// the buffer containing the original rendered pixels from kitty's own rendering. This will
|
||||
// be updated with the output color only after all custom shaders in this group have run
|
||||
public KittyTexture backbuffer;
|
||||
// The following are named textures that can be sampled from in custom
|
||||
// shaders. The persist texture will persist across frames, anything
|
||||
// written to it in render number N can be read from it in subsequent
|
||||
// renders.
|
||||
public KittyTexture a;
|
||||
public KittyTexture b;
|
||||
public KittyTexture persist;
|
||||
|
||||
public float2 pos; // the position of this pixel in the viewport (UV coordinates, [0,1] range, origin at bottom-left)
|
||||
|
||||
// Some group related uniforms. These are here rather than in
|
||||
// KittyCustomShaderData as that is shared by all groups, while these can
|
||||
// differ from group to group.
|
||||
|
||||
// The viewport for this group in the form (x, y, width, height) where (x, y) is the
|
||||
// bottom-left corner, with (0, 0) at the bottom-left of the screen and y increasing upwards
|
||||
// (UV coordinates). Defaults to (0, 0, 1, 1) when no viewport is defined for the group.
|
||||
public float4 viewport;
|
||||
// Goes from zero to one over animation_duration after the group's
|
||||
// animation starts, with the animation_curve applied, then stays at one.
|
||||
// If animation_reverse is set, it goes back down to zero after the
|
||||
// animation stops, going up and down again animation_loops - 1 more
|
||||
// times. Always zero for groups that run on every frame and for
|
||||
// groups that have neither animation_duration nor a stop duration.
|
||||
public float animation_progress;
|
||||
// The index of the current group in the pipeline.
|
||||
public int group;
|
||||
}
|
||||
// END_TYPES_DEFINITION
|
||||
@@ -0,0 +1,94 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Underwater light ray effect.
|
||||
// Adapted from https://www.shadertoy.com/view/lljGDt
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
// Luminance threshold: pixels darker than this receive the ray overlay
|
||||
static const float BLACK_BLEND_THRESHOLD = 0.4;
|
||||
|
||||
// Ray 1 source position (as fractions of viewport dimensions)
|
||||
static const float RAY1_SRC_X = 0.7;
|
||||
static const float RAY1_SRC_Y = 1.1;
|
||||
// Y component of ray 1 reference direction (X component is always 1.0)
|
||||
static const float RAY1_DIR_Y = 0.116;
|
||||
static const float RAY1_SEED_A = 36.2214;
|
||||
static const float RAY1_SEED_B = 21.11349;
|
||||
static const float RAY1_SPEED = 1.1;
|
||||
static const float RAY1_WEIGHT = 0.5; // contribution weight in final blend
|
||||
|
||||
// Ray 2 source position (as fractions of viewport dimensions)
|
||||
static const float RAY2_SRC_X = 0.8;
|
||||
static const float RAY2_SRC_Y = 1.2;
|
||||
static const float RAY2_DIR_Y = -0.241;
|
||||
static const float RAY2_SEED_A = 22.39910;
|
||||
static const float RAY2_SEED_B = 18.0234;
|
||||
static const float RAY2_SPEED = 0.9;
|
||||
static const float RAY2_WEIGHT = 0.4;
|
||||
|
||||
// Per-channel depth-attenuation: channel *= BASE + brightness * SCALE
|
||||
static const float DEPTH_R_BASE = 0.05;
|
||||
static const float DEPTH_R_SCALE = 0.8;
|
||||
static const float DEPTH_G_BASE = 0.15;
|
||||
static const float DEPTH_G_SCALE = 0.6;
|
||||
static const float DEPTH_B_BASE = 0.3;
|
||||
static const float DEPTH_B_SCALE = 0.5;
|
||||
|
||||
// Overall strength of the ray overlay on dark terminal content
|
||||
static const float OVERLAY_STRENGTH = 0.3;
|
||||
|
||||
float
|
||||
hash21(float2 p) {
|
||||
p = frac(p * float2(233.34, 851.73));
|
||||
p += dot(p, p + 23.45);
|
||||
return frac(p.x * p.y);
|
||||
}
|
||||
|
||||
float
|
||||
rayStrength(float2 raySource, float2 rayRefDir, float2 coord, float seedA, float seedB, float speed, float iTime, float resX) {
|
||||
float2 sourceToCoord = coord - raySource;
|
||||
float cosAngle = dot(normalize(sourceToCoord), rayRefDir);
|
||||
float dither = hash21(coord) * 0.015 - 0.0075;
|
||||
float ray = clamp((0.45 + 0.15 * sin(cosAngle * seedA + iTime * speed)) + (0.30 + 0.20 * cos(-cosAngle * seedB + iTime * speed)) + dither, 0.0, 1.0);
|
||||
float distFade = smoothstep(0.0, resX, resX - length(sourceToCoord));
|
||||
return ray * lerp(0.5, 1.0, distFade);
|
||||
}
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
float2 iResolution = float2(d.viewport_size_pixels) * t.viewport.zw;
|
||||
float iTime = d.wrapped_time(3600u);
|
||||
|
||||
// Convert kitty UV (y=0 at bottom) to a top-left-origin pixel coordinate,
|
||||
// matching the original shader's internal coordinate system.
|
||||
float2 coord = float2(t.pos.x, 1.0 - t.pos.y) * iResolution;
|
||||
|
||||
float2 rayPos1 = float2(iResolution.x * RAY1_SRC_X, iResolution.y * RAY1_SRC_Y);
|
||||
float2 rayRefDir1 = normalize(float2(1.0, RAY1_DIR_Y));
|
||||
|
||||
float2 rayPos2 = float2(iResolution.x * RAY2_SRC_X, iResolution.y * RAY2_SRC_Y);
|
||||
float2 rayRefDir2 = normalize(float2(1.0, RAY2_DIR_Y));
|
||||
|
||||
float4 rays1 = float4(1.0, 1.0, 1.0, 0.0) * rayStrength(rayPos1, rayRefDir1, coord, RAY1_SEED_A, RAY1_SEED_B, RAY1_SPEED, iTime, iResolution.x);
|
||||
|
||||
float4 rays2 = float4(1.0, 1.0, 1.0, 0.0) * rayStrength(rayPos2, rayRefDir2, coord, RAY2_SEED_A, RAY2_SEED_B, RAY2_SPEED, iTime, iResolution.x);
|
||||
|
||||
float4 col = rays1 * RAY1_WEIGHT + rays2 * RAY2_WEIGHT;
|
||||
|
||||
// Attenuate toward the bottom (depth) with a blue-green tint
|
||||
float brightness = t.pos.y; // 0 at screen bottom (deep), 1 at top (surface)
|
||||
col.r *= DEPTH_R_BASE + brightness * DEPTH_R_SCALE;
|
||||
col.g *= DEPTH_G_BASE + brightness * DEPTH_G_SCALE;
|
||||
col.b *= DEPTH_B_BASE + brightness * DEPTH_B_SCALE;
|
||||
|
||||
float4 terminalColor = t.backbuffer.Sample(t.pos);
|
||||
|
||||
// Overlay rays onto dark (near-black) terminal pixels; preserve bright content
|
||||
float alpha = step(length(terminalColor.rgb), BLACK_BLEND_THRESHOLD);
|
||||
float3 blendedColor = lerp(terminalColor.rgb, col.rgb * OVERLAY_STRENGTH, alpha);
|
||||
|
||||
return float4(blendedColor, terminalColor.a);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
//
|
||||
// Water caustics effect.
|
||||
|
||||
import kitty_custom_shader_types;
|
||||
|
||||
static const float TAU = 6.28318530718;
|
||||
static const int MAX_ITER = 6;
|
||||
static const float3 WATER_COLOR = float3(0.5, 0.5, 0.5); // water overlay tint
|
||||
static const float CAUSTIC_INTEN = 0.005; // caustic ripple intensity
|
||||
static const float UV_DISPLACEMENT = 0.04; // UV warp magnitude from caustics
|
||||
|
||||
public float4
|
||||
fragment_main(float4 color, KittyTextures t, KittyCustomShaderData d) {
|
||||
float wtime = d.wrapped_time(3600u) * 0.5 + 23.0;
|
||||
float2 uv = t.pos;
|
||||
|
||||
float2 p = fmod(uv * TAU, TAU) - 250.0;
|
||||
float2 i = p;
|
||||
float c = 1.0;
|
||||
|
||||
[ForceUnroll]
|
||||
for (int n = 0; n < MAX_ITER; n++) {
|
||||
float tval = wtime * (1.0 - (3.5 / float(n + 1)));
|
||||
i = p + float2(cos(tval - i.x) + sin(tval + i.y), sin(tval - i.y) + cos(tval + i.x));
|
||||
c += 1.0 / length(float2(p.x / (sin(i.x + tval) / CAUSTIC_INTEN), p.y / (cos(i.y + tval) / CAUSTIC_INTEN)));
|
||||
}
|
||||
c /= float(MAX_ITER);
|
||||
c = 1.17 - pow(c, 1.4);
|
||||
float3 col = float3(pow(abs(c), 15.0));
|
||||
col = clamp((col + WATER_COLOR) * 1.2, 0.0, 1.0);
|
||||
|
||||
// Perturb UV based on caustic value and resample
|
||||
float2 tc = float2(cos(c) - 0.75, sin(c) - 0.75) * UV_DISPLACEMENT;
|
||||
uv = clamp(uv + tc, 0.0, 1.0);
|
||||
|
||||
float4 result = t.backbuffer.Sample(uv);
|
||||
// Branchless: give fully-transparent pixels an opaque white base
|
||||
float transparent = 1.0 - step(1e-6, result.a);
|
||||
result = lerp(result, float4(1.0, 1.0, 1.0, 1.0), transparent);
|
||||
return result * float4(col, 1.0);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
import blit_common;
|
||||
import alpha_blend;
|
||||
import utils;
|
||||
|
||||
extern static const bool is_alpha_mask = false;
|
||||
extern static const bool texture_is_not_premultiplied = true;
|
||||
|
||||
|
||||
struct VSOutput {
|
||||
float2 texcoord : TEXCOORD;
|
||||
float4 position : SV_Position;
|
||||
};
|
||||
|
||||
|
||||
[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);
|
||||
return { ans.texcoord, float4(ans.position[0], ans.position[1], 0.0, 1.0) };
|
||||
}
|
||||
|
||||
uniform Sampler2D image;
|
||||
|
||||
[shader("fragment")]
|
||||
float4
|
||||
fragment_main(float2 texcoord: TEXCOORD, uniform float3 amask_fg, uniform float4 amask_bg_premult, uniform float extra_alpha)
|
||||
: SV_Target {
|
||||
float4 color = image.Sample(texcoord);
|
||||
if (is_alpha_mask) {
|
||||
color = float4(amask_fg, color.r);
|
||||
color = vec4_premul(color);
|
||||
color = alpha_blend_premul(color, amask_bg_premult);
|
||||
} else color.a *= extra_alpha;
|
||||
|
||||
if (texture_is_not_premultiplied) color = vec4_premul(color);
|
||||
|
||||
return color;
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
module hsluv;
|
||||
|
||||
// Helper Functions
|
||||
float
|
||||
divide(float num, float denom) {
|
||||
return num / (abs(denom) + 1e-15) * sign(denom);
|
||||
}
|
||||
|
||||
float3
|
||||
divide(float3 num, float3 denom) {
|
||||
return num / (abs(denom) + 1e-15) * sign(denom);
|
||||
}
|
||||
|
||||
float3
|
||||
hsluv_intersectLineLine(float3 line1x, float3 line1y, float3 line2x, float3 line2y) {
|
||||
return (line1y - line2y) / (line2x - line1x);
|
||||
}
|
||||
|
||||
float3
|
||||
hsluv_distanceFromPole(float3 pointx, float3 pointy) {
|
||||
return sqrt(pointx * pointx + pointy * pointy);
|
||||
}
|
||||
|
||||
float3
|
||||
hsluv_lengthOfRayUntilIntersect(float theta, float3 x, float3 y) {
|
||||
float3 len = divide(y, sin(theta) - x * cos(theta));
|
||||
len = lerp(len, (float3)1000.0, step(len, (float3)0.0));
|
||||
return len;
|
||||
}
|
||||
|
||||
float
|
||||
hsluv_maxSafeChromaForL(float L) {
|
||||
float3x3 m2 = float3x3(
|
||||
3.2409699419045214,
|
||||
-0.96924363628087983,
|
||||
0.055630079696993609,
|
||||
-1.5373831775700935,
|
||||
1.8759675015077207,
|
||||
-0.20397695888897657,
|
||||
-0.49861076029300328,
|
||||
0.041555057407175613,
|
||||
1.0569715142428786);
|
||||
|
||||
float sub0 = L + 16.0;
|
||||
float sub1 = sub0 * sub0 * sub0 * 0.000000641;
|
||||
float sub2 = lerp(L / 903.2962962962963, sub1, step(0.0088564516790356308, sub1));
|
||||
|
||||
float3 top1 = (284517.0 * m2[0] - 94839.0 * m2[2]) * sub2;
|
||||
float3 bottom = (632260.0 * m2[2] - 126452.0 * m2[1]) * sub2;
|
||||
float3 top2 = (838422.0 * m2[2] + 769860.0 * m2[1] + 731718.0 * m2[0]) * L * sub2;
|
||||
|
||||
float3 bounds0x = top1 / bottom;
|
||||
float3 bounds0y = top2 / bottom;
|
||||
|
||||
float3 bounds1x = top1 / (bottom + 126452.0);
|
||||
float3 bounds1y = (top2 - 769860.0 * L) / (bottom + 126452.0);
|
||||
|
||||
float3 xs0 = hsluv_intersectLineLine(bounds0x, bounds0y, -1.0 / bounds0x, (float3)0.0);
|
||||
float3 xs1 = hsluv_intersectLineLine(bounds1x, bounds1y, -1.0 / bounds1x, (float3)0.0);
|
||||
|
||||
float3 lengths0 = hsluv_distanceFromPole(xs0, bounds0y + xs0 * bounds0x);
|
||||
float3 lengths1 = hsluv_distanceFromPole(xs1, bounds1y + xs1 * bounds1x);
|
||||
|
||||
return min(lengths0.x, min(lengths1.x, min(lengths0.y, min(lengths1.y, min(lengths0.z, lengths1.z)))));
|
||||
}
|
||||
|
||||
float
|
||||
hsluv_maxChromaForLH(float L, float H) {
|
||||
float hrad = radians(H);
|
||||
|
||||
float3x3 m2 = float3x3(
|
||||
3.2409699419045214,
|
||||
-0.96924363628087983,
|
||||
0.055630079696993609,
|
||||
-1.5373831775700935,
|
||||
1.8759675015077207,
|
||||
-0.20397695888897657,
|
||||
-0.49861076029300328,
|
||||
0.041555057407175613,
|
||||
1.0569715142428786);
|
||||
|
||||
float sub1 = pow(L + 16.0, 3.0) / 1560896.0;
|
||||
float sub2 = lerp(L / 903.2962962962963, sub1, step(0.0088564516790356308, sub1));
|
||||
|
||||
float3 top1 = (284517.0 * m2[0] - 94839.0 * m2[2]) * sub2;
|
||||
float3 bottom = (632260.0 * m2[2] - 126452.0 * m2[1]) * sub2;
|
||||
float3 top2 = (838422.0 * m2[2] + 769860.0 * m2[1] + 731718.0 * m2[0]) * L * sub2;
|
||||
|
||||
float3 bound0x = top1 / bottom;
|
||||
float3 bound0y = top2 / bottom;
|
||||
|
||||
float3 bound1x = top1 / (bottom + 126452.0);
|
||||
float3 bound1y = (top2 - 769860.0 * L) / (bottom + 126452.0);
|
||||
|
||||
float3 lengths0 = hsluv_lengthOfRayUntilIntersect(hrad, bound0x, bound0y);
|
||||
float3 lengths1 = hsluv_lengthOfRayUntilIntersect(hrad, bound1x, bound1y);
|
||||
|
||||
return min(lengths0.x, min(lengths1.x, min(lengths0.y, min(lengths1.y, min(lengths0.z, lengths1.z)))));
|
||||
}
|
||||
|
||||
float3
|
||||
hsluv_fromLinear(float3 c) {
|
||||
return lerp(c * 12.92, 1.055 * pow(max(c, (float3)0), (float3)(1.0 / 2.4)) - 0.055, step(0.0031308, c));
|
||||
}
|
||||
|
||||
float3
|
||||
hsluv_toLinear(float3 c) {
|
||||
return lerp(c / 12.92, pow(max((c + 0.055) / (1.0 + 0.055), (float3)0), (float3)2.4), step(0.04045, c));
|
||||
}
|
||||
|
||||
float
|
||||
hsluv_yToL(float Y) {
|
||||
return lerp(Y * 903.2962962962963, 116.0 * pow(max(Y, 0), 1.0 / 3.0) - 16.0, step(0.0088564516790356308, Y));
|
||||
}
|
||||
|
||||
float
|
||||
hsluv_lToY(float L) {
|
||||
return lerp(L / 903.2962962962963, pow((max(L, 0) + 16.0) / 116.0, 3.0), step(8.0, L));
|
||||
}
|
||||
|
||||
float3
|
||||
xyzToRgb(float3 tuple) {
|
||||
// GLSL `mat3(args)` and Slang `float3x3(args)` agree: `v * m` in GLSL is
|
||||
// `mul(m, v)` in Slang with the arguments in the same order.
|
||||
const float3x3 m = float3x3(
|
||||
3.2409699419045214,
|
||||
-1.5373831775700935,
|
||||
-0.49861076029300328,
|
||||
-0.96924363628087983,
|
||||
1.8759675015077207,
|
||||
0.041555057407175613,
|
||||
0.055630079696993609,
|
||||
-0.20397695888897657,
|
||||
1.0569715142428786);
|
||||
return hsluv_fromLinear(mul(m, tuple));
|
||||
}
|
||||
|
||||
float3
|
||||
rgbToXyz(float3 tuple) {
|
||||
const float3x3 m = float3x3(
|
||||
0.41239079926595948,
|
||||
0.35758433938387796,
|
||||
0.18048078840183429,
|
||||
0.21263900587151036,
|
||||
0.71516867876775593,
|
||||
0.072192315360733715,
|
||||
0.019330818715591851,
|
||||
0.11919477979462599,
|
||||
0.95053215224966058);
|
||||
return mul(m, hsluv_toLinear(tuple));
|
||||
}
|
||||
|
||||
float3
|
||||
xyzToLuv(float3 tuple) {
|
||||
float X = tuple.x;
|
||||
float Y = tuple.y;
|
||||
float Z = tuple.z;
|
||||
|
||||
float L = hsluv_yToL(Y);
|
||||
float div = 1.0 / max(dot(tuple, float3(1, 15, 3)), 1e-15);
|
||||
|
||||
return float3(1.0, (52.0 * (X * div) - 2.57179), (117.0 * (Y * div) - 6.08816)) * L;
|
||||
}
|
||||
|
||||
float3
|
||||
luvToXyz(float3 tuple) {
|
||||
float L = tuple.x;
|
||||
|
||||
float U = divide(tuple.y, 13.0 * L) + 0.19783000664283681;
|
||||
float V = divide(tuple.z, 13.0 * L) + 0.468319994938791;
|
||||
|
||||
float Y = hsluv_lToY(L);
|
||||
float X = 2.25 * U * Y / V;
|
||||
float Z = (3.0 / V - 5.0) * Y - (X / 3.0);
|
||||
|
||||
return float3(X, Y, Z);
|
||||
}
|
||||
|
||||
float3
|
||||
luvToLch(float3 tuple) {
|
||||
float L = tuple.x;
|
||||
float U = tuple.y;
|
||||
float V = tuple.z;
|
||||
|
||||
float C = length(tuple.yz);
|
||||
float H = degrees(atan2(V, U)); // Slang standard library uses atan2(y, x)
|
||||
H += 360.0 * step(H, 0.0);
|
||||
|
||||
return float3(L, C, H);
|
||||
}
|
||||
|
||||
float3
|
||||
lchToLuv(float3 tuple) {
|
||||
float hrad = radians(tuple.z);
|
||||
return float3(tuple.x, cos(hrad) * tuple.y, sin(hrad) * tuple.y);
|
||||
}
|
||||
|
||||
float3
|
||||
hsluvToLch(float3 tuple) {
|
||||
tuple.y *= hsluv_maxChromaForLH(tuple.z, tuple.x) * 0.01;
|
||||
return tuple.zyx;
|
||||
}
|
||||
|
||||
float3
|
||||
lchToHsluv(float3 tuple) {
|
||||
tuple.y = divide(tuple.y, hsluv_maxChromaForLH(tuple.x, tuple.z) * 0.01);
|
||||
return tuple.zyx;
|
||||
}
|
||||
|
||||
float3
|
||||
lchToRgb(float3 tuple) {
|
||||
return xyzToRgb(luvToXyz(lchToLuv(tuple)));
|
||||
}
|
||||
|
||||
float3
|
||||
rgbToLch(float3 tuple) {
|
||||
return luvToLch(xyzToLuv(rgbToXyz(tuple)));
|
||||
}
|
||||
|
||||
public float3
|
||||
hsluvToRgb(float3 tuple) {
|
||||
return lchToRgb(hsluvToLch(tuple));
|
||||
}
|
||||
|
||||
public float3
|
||||
rgbToHsluv(float3 tuple) {
|
||||
return lchToHsluv(rgbToLch(tuple));
|
||||
}
|
||||
|
||||
float3
|
||||
luvToRgb(float3 tuple) {
|
||||
return xyzToRgb(luvToXyz(tuple));
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
// Renders images whose pixels are indices into the terminal color palette, so
|
||||
// that they change automatically when the terminal colors change. This is a
|
||||
// separate program from graphics.slang so that rendering of normal images has
|
||||
// no overhead because of it.
|
||||
|
||||
import blit_common;
|
||||
import background;
|
||||
|
||||
// False for the variant used when the image is drawn at its natural size,
|
||||
// which needs only a single pixel read per fragment.
|
||||
extern static const bool is_scaled = true;
|
||||
|
||||
struct VSOutput {
|
||||
float2 texcoord : TEXCOORD;
|
||||
float4 position : SV_Position;
|
||||
};
|
||||
|
||||
[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);
|
||||
return { ans.texcoord, float4(ans.position[0], ans.position[1], 0.0, 1.0) };
|
||||
}
|
||||
|
||||
// The red channel is the palette index and, when has_alpha is non-zero, the
|
||||
// green channel is the straight alpha.
|
||||
uniform Sampler2D<uint4> image;
|
||||
|
||||
float4
|
||||
premult_color_at(int2 pos, uint has_alpha) {
|
||||
uint4 px = image[pos];
|
||||
float alpha = has_alpha != 0 ? float(px.g) / 255.0 : 1.0;
|
||||
return float4(indexed_image_color(px.r) * alpha, alpha);
|
||||
}
|
||||
|
||||
[shader("fragment")]
|
||||
float4
|
||||
fragment_main(float2 texcoord: TEXCOORD, uniform uint has_alpha, uniform float extra_alpha)
|
||||
: SV_Target {
|
||||
// Integer textures cannot be filtered and anyway the palette lookup must
|
||||
// happen before interpolation, so do bilinear filtering here.
|
||||
int width, height;
|
||||
image.GetDimensions(width, height);
|
||||
const int2 limit = int2(width - 1, height - 1);
|
||||
// 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;
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
module linear2srgb;
|
||||
|
||||
// Scalar sRGB to Linear conversion
|
||||
public float
|
||||
srgb2linear(float x) {
|
||||
float lower = x / 12.92;
|
||||
float upper = pow((x + 0.055f) / 1.055f, 2.4f);
|
||||
|
||||
// GLSL mix() is replaced by Slang's lerp()
|
||||
return lerp(lower, upper, step(0.04045f, x));
|
||||
}
|
||||
|
||||
// Scalar Linear to sRGB conversion
|
||||
public float
|
||||
linear2srgb(float x) {
|
||||
float lower = 12.92 * x;
|
||||
float upper = 1.055 * pow(x, 1.0f / 2.4f) - 0.055f;
|
||||
|
||||
return lerp(lower, upper, step(0.0031308f, x));
|
||||
}
|
||||
|
||||
// Vector Linear to sRGB conversion
|
||||
public float3
|
||||
linear2srgb(float3 x) {
|
||||
float3 lower = 12.92 * x;
|
||||
float3 upper = 1.055 * pow(x, float3(1.0f / 2.4f)) - 0.055f;
|
||||
|
||||
return lerp(lower, upper, step(float3(0.0031308f), x));
|
||||
}
|
||||
|
||||
// Vector sRGB to Linear conversion
|
||||
public float3
|
||||
srgb2linear(float3 c) {
|
||||
// You can call the scalar version per-component,
|
||||
// or pass the whole vector if you overload it for float3.
|
||||
return float3(srgb2linear(c.r), srgb2linear(c.g), srgb2linear(c.b));
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
// https://github.com/shader-slang/slang/issues/11874
|
||||
// warnings-disable: 41012
|
||||
|
||||
import utils;
|
||||
import background;
|
||||
|
||||
// This shader colors the compensatory window padding (the thin strips that
|
||||
// appear when the window size is not an exact multiple of the cell size) so
|
||||
// that each strip matches the background of its neighboring cell. It re-uses
|
||||
// the cell VAO (colors/sprite_idx/is_selected instanced attributes) and the
|
||||
// background module's padding_background_premul() to compute the color.
|
||||
//
|
||||
// Each draw call covers one or two parallel strips (e.g. top+bottom or
|
||||
// left+right). The cell VAO attributes are pre-packed into a dedicated
|
||||
// padding buffer so instance i reads strip-0 cells for i < along_count and
|
||||
// strip-1 cells for i >= along_count. All per-strip selection (geometry and
|
||||
// cell index) is done branch-free via lerp on strip_f ∈ {0.0, 1.0}.
|
||||
|
||||
// Corner indicator per quad vertex, matching cell_pos_map in background.slang.
|
||||
// .x: 0 -> left, 1 -> right ; .y: 0 -> top, 1 -> bottom
|
||||
static const uint2 pad_pos_map[4] = {
|
||||
uint2(1u, 0u), // right, top
|
||||
uint2(1u, 1u), // right, bottom
|
||||
uint2(0u, 1u), // left, bottom
|
||||
uint2(0u, 0u) // left, top
|
||||
};
|
||||
|
||||
struct VertexOutput {
|
||||
float4 color_premul : COLOR_PREMUL;
|
||||
float4 position : SV_Position;
|
||||
};
|
||||
|
||||
[shader("vertex")]
|
||||
VertexOutput
|
||||
vertex_main(
|
||||
[[vk::location(0)]] uint3 colors,
|
||||
[[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, ) {
|
||||
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;
|
||||
|
||||
// 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);
|
||||
|
||||
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;
|
||||
|
||||
// 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 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 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);
|
||||
float across_v = lerp(chosen_across.x, chosen_across.y, a);
|
||||
|
||||
// Horizontal strip -> position is (along, across); vertical -> (across, along).
|
||||
vo.position = float4(lerp(across_v, along, h), lerp(along, across_v, h), 0.0, 1.0);
|
||||
return vo;
|
||||
}
|
||||
|
||||
[shader("fragment")]
|
||||
float4
|
||||
fragment_main(float4 color_premul: COLOR_PREMUL)
|
||||
: SV_Target {
|
||||
return color_premul;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
import alpha_blend;
|
||||
|
||||
// The four corners of the full viewport quad in NDC, in triangle fan order:
|
||||
// top-right, bottom-right, bottom-left, top-left.
|
||||
// Note: deliberately a table of ready made positions rather than a dynamic
|
||||
// index into a rect vector. slangc inlines a static const vector into the
|
||||
// generated GLSL as an anonymous vec4() constructor, and on the macOS AMD
|
||||
// driver (GL_RENDERER 4.1 ATI-5.5.20) dynamically indexing that temporary
|
||||
// produced 0 for the right and bottom components, collapsing this quad to its
|
||||
// top left quadrant so only half of each rounded border/scrollbar was drawn.
|
||||
// Indexing a *named* vector dynamically is fine there, borders.slang does it.
|
||||
// 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) };
|
||||
|
||||
[shader("vertex")]
|
||||
float4
|
||||
vertex_main(uint vertex_id: SV_VertexID)
|
||||
: SV_Position {
|
||||
return float4(vertex_pos_map[vertex_id], 0, 1);
|
||||
}
|
||||
|
||||
// Signed distance function for a rounded rectangle
|
||||
float
|
||||
rounded_rectangle_sdf(float2 p, float2 b, float r) {
|
||||
// signed distance field
|
||||
// first term is used for points outside the rectangle
|
||||
float2 q = abs(p) - b;
|
||||
return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - 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];
|
||||
|
||||
// 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;
|
||||
|
||||
// Calculate distance to rounded rectangle
|
||||
float dist = rounded_rectangle_sdf(position, size * 0.5 - corner_radius, corner_radius);
|
||||
|
||||
// The border is outer - inner rects
|
||||
float outer_edge = -dist;
|
||||
float inner_edge = outer_edge - thickness;
|
||||
|
||||
// Smooth borders (anti-alias)
|
||||
static const float step_size = 1.0;
|
||||
float outer_coverage = smoothstep(-step_size, step_size, outer_edge);
|
||||
float alpha = outer_coverage - smoothstep(-step_size, step_size, inner_edge);
|
||||
|
||||
float4 ans = 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);
|
||||
// pre-multiplied output
|
||||
return alpha_blend(ans, under);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
import blit_common;
|
||||
import linear2srgb;
|
||||
|
||||
struct VSOutput {
|
||||
float2 texcoord : TEXCOORD;
|
||||
float4 position : SV_Position;
|
||||
};
|
||||
|
||||
|
||||
[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);
|
||||
return { ans.texcoord, float4(ans.position[0], ans.position[1], 0.0, 1.0) };
|
||||
}
|
||||
|
||||
uniform Sampler2D image;
|
||||
|
||||
float3
|
||||
safe_unpremult_to_linear(float4 s) {
|
||||
// Avoid division by zero by replacing 0.0 alpha with 1.0.
|
||||
// If alpha is 0.0, the division is safe, and lerp masks the result to 0.0 anyway.
|
||||
float safe_alpha = lerp(1.0f, s.a, step(0.00001f, s.a));
|
||||
float3 unpremult = s.rgb / safe_alpha;
|
||||
// Select between the computed linear color and float3(0.0) based on alpha presence
|
||||
return lerp(float3(0.0f), srgb2linear(unpremult), step(0.00001f, s.a));
|
||||
}
|
||||
|
||||
[shader("fragment")]
|
||||
float4
|
||||
fragment_main(float2 texcoord: TEXCOORD, uniform float2 src_size)
|
||||
: SV_Target {
|
||||
float4 s00, s10, s01, s11;
|
||||
float2 texel_size = 1.0 / src_size;
|
||||
|
||||
// Use Slang target switches to dynamically compile for specific backend features
|
||||
__target_switch {
|
||||
// Modern backends with full texture gathering capabilities
|
||||
case spirv:
|
||||
case hlsl:
|
||||
case metal: {
|
||||
float2 gather_coord = texcoord - (0.5 * texel_size);
|
||||
|
||||
float4 r_gather = image.GatherRed(gather_coord);
|
||||
float4 g_gather = image.GatherGreen(gather_coord);
|
||||
float4 b_gather = image.GatherBlue(gather_coord);
|
||||
float4 a_gather = image.GatherAlpha(gather_coord);
|
||||
|
||||
s00 = float4(r_gather.w, g_gather.w, b_gather.w, a_gather.w); // Bottom-Left
|
||||
s10 = float4(r_gather.z, g_gather.z, b_gather.z, a_gather.z); // Bottom-Right
|
||||
s01 = float4(r_gather.x, g_gather.x, b_gather.x, a_gather.x); // Top-Left
|
||||
s11 = float4(r_gather.y, g_gather.y, b_gather.y, a_gather.y); // Top-Right
|
||||
}
|
||||
// Fallback for older targets or legacy GLSL versions
|
||||
default: {
|
||||
s00 = image.Sample(texcoord + float2(-0.25, -0.25) * texel_size);
|
||||
s10 = image.Sample(texcoord + float2(0.25, -0.25) * texel_size);
|
||||
s01 = image.Sample(texcoord + float2(-0.25, 0.25) * texel_size);
|
||||
s11 = image.Sample(texcoord + float2(0.25, 0.25) * texel_size);
|
||||
}
|
||||
}
|
||||
|
||||
// Unpremultiply and convert to linear for each sample
|
||||
float3 linear00 = safe_unpremult_to_linear(s00);
|
||||
float3 linear10 = safe_unpremult_to_linear(s10);
|
||||
float3 linear01 = safe_unpremult_to_linear(s01);
|
||||
float3 linear11 = safe_unpremult_to_linear(s11);
|
||||
|
||||
// Average the alpha values
|
||||
float avg_alpha = (s00.a + s10.a + s01.a + s11.a) * 0.25;
|
||||
|
||||
// For proper downsampling with transparency, weight colors by their alpha
|
||||
float3 weighted_sum = linear00 * s00.a + linear10 * s10.a + linear01 * s01.a + linear11 * s11.a;
|
||||
float total_weight = s00.a + s10.a + s01.a + s11.a;
|
||||
|
||||
// Calculate the weighted average color in linear space
|
||||
float safe_total_weight = lerp(1.0f, total_weight, step(0.00001f, total_weight));
|
||||
float3 avg_linear = lerp(float3(0.0f), weighted_sum / safe_total_weight, step(0.00001f, total_weight));
|
||||
|
||||
// Convert back to sRGB
|
||||
float3 srgb_color = linear2srgb(avg_linear);
|
||||
|
||||
// Output unpremultiplied sRGB color
|
||||
return float4(srgb_color, avg_alpha);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,31 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
// Main Vertex Shader Entry Point
|
||||
[shader("vertex")]
|
||||
float4
|
||||
vertex_main(
|
||||
uint vertex_id: SV_VertexID,
|
||||
uniform float4 edges, // [ left, top, right, bottom ]
|
||||
)
|
||||
: SV_Position {
|
||||
// Extract boundaries from the edges vector
|
||||
float left = edges[0];
|
||||
float top = edges[1];
|
||||
float right = edges[2];
|
||||
float bottom = 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) };
|
||||
|
||||
// Calculate final position
|
||||
return float4(pos_map[vertex_id], 0.0, 1.0);
|
||||
}
|
||||
|
||||
[shader("fragment")]
|
||||
float4
|
||||
fragment_main(uniform float4 tint_color)
|
||||
: SV_Target {
|
||||
return tint_color;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
struct VertexOutput {
|
||||
float2 frag_pos : TEXCOORD;
|
||||
float4 position : SV_Position;
|
||||
};
|
||||
|
||||
// Main Vertex Shader Entry Point
|
||||
[shader("vertex")]
|
||||
VertexOutput
|
||||
vertex_main(uint vertex_id: SV_VertexID, uniform float4 x_coords, uniform float4 y_coords) {
|
||||
VertexOutput output;
|
||||
float2 pos = float2(x_coords[vertex_id], y_coords[vertex_id]);
|
||||
output.position = float4(pos, 1.0, 1.0);
|
||||
output.frag_pos = pos;
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
// 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)
|
||||
: SV_Target {
|
||||
float opacity = 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]);
|
||||
|
||||
// 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);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
#language slang 2026
|
||||
// Copyright (C) 2026 Kovid Goyal <kovid at kovidgoyal.net>
|
||||
// Distributed under terms of the GPLv3 license.
|
||||
|
||||
module utils;
|
||||
|
||||
// Return 0 if x < 1 otherwise 1
|
||||
public __generic<T : __BuiltinFloatingPointType, int N = 1> vector<T, N>
|
||||
zero_or_one(vector<T, N> x) {
|
||||
return step((vector<T, N>)1.0f, x);
|
||||
}
|
||||
|
||||
// condition must be zero or one. When 1 thenval is returned otherwise elseval
|
||||
public __generic<T : __BuiltinFloatingPointType, int N = 1> vector<T, N>
|
||||
if_one_then(vector<T, N> condition, vector<T, N> thenval, vector<T, N> elseval) {
|
||||
return lerp(elseval, thenval, condition);
|
||||
}
|
||||
|
||||
// a < b ? thenval : elseval
|
||||
public __generic<T : __BuiltinFloatingPointType, int N = 1> vector<T, N>
|
||||
if_less_than(vector<T, N> a, vector<T, N> b, vector<T, N> thenval, vector<T, N> elseval) {
|
||||
return lerp(thenval, elseval, step(b, a));
|
||||
}
|
||||
|
||||
// Replaces vec4(rgb * a, a)
|
||||
public float4
|
||||
vec4_premul(float3 rgb, float a) {
|
||||
return float4(rgb * a, a);
|
||||
}
|
||||
|
||||
// Overloaded variation replacing vec4(rgba.rgb * rgba.a, rgba.a)
|
||||
public float4
|
||||
vec4_premul(float4 rgba) {
|
||||
return float4(rgba.rgb * rgba.a, rgba.a);
|
||||
}
|
||||
Executable
+76
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
# Map the custom extensions to the required glslangValidator stage strings
|
||||
stage_mapping = {
|
||||
'.vert.glsl': 'vert',
|
||||
'.frag.glsl': 'frag',
|
||||
'.vertex.glsl': 'vert',
|
||||
'.fragment.glsl': 'frag',
|
||||
}
|
||||
|
||||
|
||||
def validation_command_for_file(path: str | Path) -> list[str]:
|
||||
file_path = Path(path)
|
||||
matched_ext = next(ext for ext in stage_mapping if file_path.name.endswith(ext))
|
||||
stage = stage_mapping[matched_ext]
|
||||
return ['glslangValidator', '-S', stage, str(file_path)]
|
||||
|
||||
|
||||
def validate_glsl_files(shader_files: Iterable[str | Path], verbose: bool = False) -> None:
|
||||
error_count = 0
|
||||
|
||||
# Process each shader file
|
||||
for file_path in sorted(Path(f) for f in shader_files):
|
||||
# Identify extension matching suffix
|
||||
if verbose:
|
||||
print(f'Validating: {file_path.name}')
|
||||
result = subprocess.run(validation_command_for_file(file_path))
|
||||
|
||||
# Check exit code
|
||||
if result.returncode != 0:
|
||||
error_count += 1
|
||||
print(f'❌ Failed: {file_path.name}', file=sys.stderr)
|
||||
else:
|
||||
if verbose:
|
||||
print(f'✅ Passed: {file_path.name}')
|
||||
|
||||
if verbose:
|
||||
print('-' * 50)
|
||||
|
||||
# Print execution summary
|
||||
if error_count == 0:
|
||||
if verbose:
|
||||
print('Success: All shaders validated successfully!')
|
||||
else:
|
||||
raise SystemExit(f'Failure: {error_count} shader(s) failed validation.')
|
||||
|
||||
|
||||
def validate_glsl_dir(directory_path: str, verbose: bool = False) -> None:
|
||||
"""
|
||||
Validates all GLSL shaders in the specified directory with names matching
|
||||
name.vert.glsl or name.frag.glsl using glslangValidator.
|
||||
"""
|
||||
target_dir = Path(directory_path)
|
||||
|
||||
if not target_dir.is_dir():
|
||||
raise SystemExit(f"Error: Directory '{directory_path}' does not exist.")
|
||||
|
||||
# Find all files matching the patterns
|
||||
shader_files: list[Path] = []
|
||||
for ext in stage_mapping.keys():
|
||||
shader_files.extend(target_dir.glob(f'*{ext}'))
|
||||
|
||||
if not shader_files:
|
||||
if verbose:
|
||||
print(f"No matching shaders (*.vert.glsl or *.frag.glsl) found in '{target_dir}'.")
|
||||
return
|
||||
validate_glsl_files(shader_files)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
dir_to_scan = sys.argv[1] if len(sys.argv) > 1 else 'shaders'
|
||||
validate_glsl_dir(dir_to_scan, verbose=True)
|
||||
Reference in new issue
Block a user