Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T02:36:26.639Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

shaders.wgsl

1365 lines · 52.1 KB · text
1/* Functions useful for debugging:
2
3// A heat map color for debugging (blue -> cyan -> green -> yellow -> red).
4fn heat_map_color(value: f32, minValue: f32, maxValue: f32, position: vec2<f32>) -> vec4<f32> {
5    // Normalize value to 0-1 range
6    let t = clamp((value - minValue) / (maxValue - minValue), 0.0, 1.0);
7
8    // Heat map color calculation
9    let r = t * t;
10    let g = 4.0 * t * (1.0 - t);
11    let b = (1.0 - t) * (1.0 - t);
12    let heat_color = vec3<f32>(r, g, b);
13
14    // Create a checkerboard pattern (black and white)
15    let sum = floor(position.x / 3) + floor(position.y / 3);
16    let is_odd = fract(sum * 0.5); // 0.0 for even, 0.5 for odd
17    let checker_value = is_odd * 2.0; // 0.0 for even, 1.0 for odd
18    let checker_color = vec3<f32>(checker_value);
19
20    // Determine if value is in range (1.0 if in range, 0.0 if out of range)
21    let in_range = step(minValue, value) * step(value, maxValue);
22
23    // Mix checkerboard and heat map based on whether value is in range
24    let final_color = mix(checker_color, heat_color, in_range);
25
26    return vec4<f32>(final_color, 1.0);
27}
28
29*/
30
31// Contrast and gamma correction adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.hlsl
32// Copyright (c) Microsoft Corporation.
33// Licensed under the MIT license.
34fn color_brightness(color: vec3<f32>) -> f32 {
35    // REC. 601 luminance coefficients for perceived brightness
36    return dot(color, vec3<f32>(0.30, 0.59, 0.11));
37}
38
39fn light_on_dark_contrast(enhancedContrast: f32, color: vec3<f32>) -> f32 {
40    let brightness = color_brightness(color);
41    let multiplier = saturate(4.0 * (0.75 - brightness));
42    return enhancedContrast * multiplier;
43}
44
45fn enhance_contrast(alpha: f32, k: f32) -> f32 {
46    return alpha * (k + 1.0) / (alpha * k + 1.0);
47}
48
49fn enhance_contrast3(alpha: vec3<f32>, k: f32) -> vec3<f32> {
50    return alpha * (k + 1.0) / (alpha * k + 1.0);
51}
52
53fn apply_alpha_correction(a: f32, b: f32, g: vec4<f32>) -> f32 {
54    let brightness_adjustment = g.x * b + g.y;
55    let correction = brightness_adjustment * a + (g.z * b + g.w);
56    return a + a * (1.0 - a) * correction;
57}
58
59fn apply_alpha_correction3(a: vec3<f32>, b: vec3<f32>, g: vec4<f32>) -> vec3<f32> {
60    let brightness_adjustment = g.x * b + g.y;
61    let correction = brightness_adjustment * a + (g.z * b + g.w);
62    return a + a * (1.0 - a) * correction;
63}
64
65fn apply_contrast_and_gamma_correction(sample: f32, color: vec3<f32>, enhanced_contrast_factor: f32, gamma_ratios: vec4<f32>) -> f32 {
66    let enhanced_contrast = light_on_dark_contrast(enhanced_contrast_factor, color);
67    let brightness = color_brightness(color);
68
69    let contrasted = enhance_contrast(sample, enhanced_contrast);
70    return apply_alpha_correction(contrasted, brightness, gamma_ratios);
71}
72
73fn apply_contrast_and_gamma_correction3(sample: vec3<f32>, color: vec3<f32>, enhanced_contrast_factor: f32, gamma_ratios: vec4<f32>) -> vec3<f32> {
74    let enhanced_contrast = light_on_dark_contrast(enhanced_contrast_factor, color);
75
76    let contrasted = enhance_contrast3(sample, enhanced_contrast);
77    return apply_alpha_correction3(contrasted, color, gamma_ratios);
78}
79
80struct GlobalParams {
81    viewport_size: vec2<f32>,
82    premultiplied_alpha: u32,
83    pad: u32,
84}
85
86struct GammaParams {
87    gamma_ratios: vec4<f32>,
88    grayscale_enhanced_contrast: f32,
89    subpixel_enhanced_contrast: f32,
90    is_bgr: u32,
91    pad: u32,
92}
93
94@group(0) @binding(0) var<uniform> globals: GlobalParams;
95@group(0) @binding(1) var<uniform> gamma_params: GammaParams;
96@group(1) @binding(1) var t_sprite: texture_2d<f32>;
97@group(1) @binding(2) var s_sprite: sampler;
98
99const M_PI_F: f32 = 3.1415926;
100const GRAYSCALE_FACTORS: vec3<f32> = vec3<f32>(0.2126, 0.7152, 0.0722);
101
102struct Bounds {
103    origin: vec2<f32>,
104    size: vec2<f32>,
105}
106
107struct Corners {
108    top_left: f32,
109    top_right: f32,
110    bottom_right: f32,
111    bottom_left: f32,
112}
113
114struct Edges {
115    top: f32,
116    right: f32,
117    bottom: f32,
118    left: f32,
119}
120
121struct Hsla {
122    h: f32,
123    s: f32,
124    l: f32,
125    a: f32,
126}
127
128struct LinearColorStop {
129    color: Hsla,
130    percentage: f32,
131}
132
133struct Background {
134    // 0u is Solid
135    // 1u is LinearGradient
136    // 2u is PatternSlash
137    // 3u is Checkerboard
138    tag: u32,
139    // 0u is sRGB linear color
140    // 1u is Oklab color
141    color_space: u32,
142    solid: Hsla,
143    gradient_angle_or_pattern_height: f32,
144    colors: array<LinearColorStop, 2>,
145    pad: u32,
146}
147
148struct AtlasTextureId {
149    index: u32,
150    kind: u32,
151}
152
153struct AtlasBounds {
154    origin: vec2<i32>,
155    size: vec2<i32>,
156}
157
158struct AtlasTile {
159    texture_id: AtlasTextureId,
160    tile_id: u32,
161    padding: u32,
162    bounds: AtlasBounds,
163}
164
165struct TransformationMatrix {
166    rotation_scale: mat2x2<f32>,
167    translation: vec2<f32>,
168}
169
170fn to_device_position_impl(position: vec2<f32>) -> vec4<f32> {
171    let device_position = position / globals.viewport_size * vec2<f32>(2.0, -2.0) + vec2<f32>(-1.0, 1.0);
172    return vec4<f32>(device_position, 0.0, 1.0);
173}
174
175fn to_device_position(unit_vertex: vec2<f32>, bounds: Bounds) -> vec4<f32> {
176    let position = unit_vertex * vec2<f32>(bounds.size) + bounds.origin;
177    return to_device_position_impl(position);
178}
179
180fn to_device_position_transformed(unit_vertex: vec2<f32>, bounds: Bounds, transform: TransformationMatrix) -> vec4<f32> {
181    let position = unit_vertex * vec2<f32>(bounds.size) + bounds.origin;
182    //Note: Rust side stores it as row-major, so transposing here
183    let transformed = transpose(transform.rotation_scale) * position + transform.translation;
184    return to_device_position_impl(transformed);
185}
186
187fn to_tile_position(unit_vertex: vec2<f32>, tile: AtlasTile) -> vec2<f32> {
188  let atlas_size = vec2<f32>(textureDimensions(t_sprite, 0));
189  return (vec2<f32>(tile.bounds.origin) + unit_vertex * vec2<f32>(tile.bounds.size)) / atlas_size;
190}
191
192fn distance_from_clip_rect_impl(position: vec2<f32>, clip_bounds: Bounds) -> vec4<f32> {
193    let tl = position - clip_bounds.origin;
194    let br = clip_bounds.origin + clip_bounds.size - position;
195    return vec4<f32>(tl.x, br.x, tl.y, br.y);
196}
197
198fn distance_from_clip_rect(unit_vertex: vec2<f32>, bounds: Bounds, clip_bounds: Bounds) -> vec4<f32> {
199    let position = unit_vertex * vec2<f32>(bounds.size) + bounds.origin;
200    return distance_from_clip_rect_impl(position, clip_bounds);
201}
202
203fn distance_from_clip_rect_transformed(unit_vertex: vec2<f32>, bounds: Bounds, clip_bounds: Bounds, transform: TransformationMatrix) -> vec4<f32> {
204    let position = unit_vertex * vec2<f32>(bounds.size) + bounds.origin;
205    let transformed = transpose(transform.rotation_scale) * position + transform.translation;
206    return distance_from_clip_rect_impl(transformed, clip_bounds);
207}
208
209// https://gamedev.stackexchange.com/questions/92015/optimized-linear-to-srgb-glsl
210fn srgb_to_linear(srgb: vec3<f32>) -> vec3<f32> {
211    let cutoff = srgb < vec3<f32>(0.04045);
212    let higher = pow((srgb + vec3<f32>(0.055)) / vec3<f32>(1.055), vec3<f32>(2.4));
213    let lower = srgb / vec3<f32>(12.92);
214    return select(higher, lower, cutoff);
215}
216
217fn srgb_to_linear_component(a: f32) -> f32 {
218    let cutoff = a < 0.04045;
219    let higher = pow((a + 0.055) / 1.055, 2.4);
220    let lower = a / 12.92;
221    return select(higher, lower, cutoff);
222}
223
224fn linear_to_srgb(linear: vec3<f32>) -> vec3<f32> {
225    let cutoff = linear < vec3<f32>(0.0031308);
226    let higher = vec3<f32>(1.055) * pow(linear, vec3<f32>(1.0 / 2.4)) - vec3<f32>(0.055);
227    let lower = linear * vec3<f32>(12.92);
228    return select(higher, lower, cutoff);
229}
230
231/// Convert a linear color to sRGBA space.
232fn linear_to_srgba(color: vec4<f32>) -> vec4<f32> {
233    return vec4<f32>(linear_to_srgb(color.rgb), color.a);
234}
235
236/// Convert a sRGBA color to linear space.
237fn srgba_to_linear(color: vec4<f32>) -> vec4<f32> {
238    return vec4<f32>(srgb_to_linear(color.rgb), color.a);
239}
240
241/// Hsla to linear RGBA conversion.
242fn hsla_to_rgba(hsla: Hsla) -> vec4<f32> {
243    let h = hsla.h * 6.0; // Now, it's an angle but scaled in [0, 6) range
244    let s = hsla.s;
245    let l = hsla.l;
246    let a = hsla.a;
247
248    let c = (1.0 - abs(2.0 * l - 1.0)) * s;
249    let x = c * (1.0 - abs(h % 2.0 - 1.0));
250    let m = l - c / 2.0;
251    var color = vec3<f32>(m);
252
253    if (h >= 0.0 && h < 1.0) {
254        color.r += c;
255        color.g += x;
256    } else if (h >= 1.0 && h < 2.0) {
257        color.r += x;
258        color.g += c;
259    } else if (h >= 2.0 && h < 3.0) {
260        color.g += c;
261        color.b += x;
262    } else if (h >= 3.0 && h < 4.0) {
263        color.g += x;
264        color.b += c;
265    } else if (h >= 4.0 && h < 5.0) {
266        color.r += x;
267        color.b += c;
268    } else {
269        color.r += c;
270        color.b += x;
271    }
272
273    return vec4<f32>(color, a);
274}
275
276/// Convert a linear sRGB to Oklab space.
277/// Reference: https://bottosson.github.io/posts/oklab/#converting-from-linear-srgb-to-oklab
278fn linear_srgb_to_oklab(color: vec4<f32>) -> vec4<f32> {
279	let l = 0.4122214708 * color.r + 0.5363325363 * color.g + 0.0514459929 * color.b;
280	let m = 0.2119034982 * color.r + 0.6806995451 * color.g + 0.1073969566 * color.b;
281	let s = 0.0883024619 * color.r + 0.2817188376 * color.g + 0.6299787005 * color.b;
282
283	let l_ = pow(l, 1.0 / 3.0);
284	let m_ = pow(m, 1.0 / 3.0);
285	let s_ = pow(s, 1.0 / 3.0);
286
287	return vec4<f32>(
288		0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
289		1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
290		0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
291		color.a
292	);
293}
294
295/// Convert an Oklab color to linear sRGB space.
296fn oklab_to_linear_srgb(color: vec4<f32>) -> vec4<f32> {
297	let l_ = color.r + 0.3963377774 * color.g + 0.2158037573 * color.b;
298	let m_ = color.r - 0.1055613458 * color.g - 0.0638541728 * color.b;
299	let s_ = color.r - 0.0894841775 * color.g - 1.2914855480 * color.b;
300
301	let l = l_ * l_ * l_;
302	let m = m_ * m_ * m_;
303	let s = s_ * s_ * s_;
304
305	return vec4<f32>(
306		4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
307		-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
308		-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s,
309		color.a
310	);
311}
312
313fn over(below: vec4<f32>, above: vec4<f32>) -> vec4<f32> {
314    let alpha = above.a + below.a * (1.0 - above.a);
315    let color = (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha;
316    return vec4<f32>(color, alpha);
317}
318
319// A standard gaussian function, used for weighting samples
320fn gaussian(x: f32, sigma: f32) -> f32{
321    return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * M_PI_F) * sigma);
322}
323
324// This approximates the error function, needed for the gaussian integral
325fn erf(v: vec2<f32>) -> vec2<f32> {
326    let s = sign(v);
327    let a = abs(v);
328    let r1 = 1.0 + (0.278393 + (0.230389 + (0.000972 + 0.078108 * a) * a) * a) * a;
329    let r2 = r1 * r1;
330    return s - s / (r2 * r2);
331}
332
333fn blur_along_x(x: f32, y: f32, sigma: f32, corner: f32, half_size: vec2<f32>) -> f32 {
334  let delta = min(half_size.y - corner - abs(y), 0.0);
335  let curved = half_size.x - corner + sqrt(max(0.0, corner * corner - delta * delta));
336  let integral = 0.5 + 0.5 * erf((x + vec2<f32>(-curved, curved)) * (sqrt(0.5) / sigma));
337  return integral.y - integral.x;
338}
339
340// Selects corner radius based on quadrant.
341fn pick_corner_radius(center_to_point: vec2<f32>, radii: Corners) -> f32 {
342    if (center_to_point.x < 0.0) {
343        if (center_to_point.y < 0.0) {
344            return radii.top_left;
345        } else {
346            return radii.bottom_left;
347        }
348    } else {
349        if (center_to_point.y < 0.0) {
350            return radii.top_right;
351        } else {
352            return radii.bottom_right;
353        }
354    }
355}
356
357// Signed distance of the point to the quad's border - positive outside the
358// border, and negative inside.
359//
360// See comments on similar code using `quad_sdf_impl` in `fs_quad` for
361// explanation.
362fn quad_sdf(point: vec2<f32>, bounds: Bounds, corner_radii: Corners) -> f32 {
363    let half_size = bounds.size / 2.0;
364    let center = bounds.origin + half_size;
365    let center_to_point = point - center;
366    let corner_radius = pick_corner_radius(center_to_point, corner_radii);
367    let corner_to_point = abs(center_to_point) - half_size;
368    let corner_center_to_point = corner_to_point + corner_radius;
369    return quad_sdf_impl(corner_center_to_point, corner_radius);
370}
371
372fn quad_sdf_impl(corner_center_to_point: vec2<f32>, corner_radius: f32) -> f32 {
373    if (corner_radius == 0.0) {
374        // Fast path for unrounded corners.
375        return max(corner_center_to_point.x, corner_center_to_point.y);
376    } else {
377        // Signed distance of the point from a quad that is inset by corner_radius.
378        // It is negative inside this quad, and positive outside.
379        let signed_distance_to_inset_quad =
380            // 0 inside the inset quad, and positive outside.
381            length(max(vec2<f32>(0.0), corner_center_to_point)) +
382            // 0 outside the inset quad, and negative inside.
383            min(0.0, max(corner_center_to_point.x, corner_center_to_point.y));
384
385        return signed_distance_to_inset_quad - corner_radius;
386    }
387}
388
389// Abstract away the final color transformation based on the
390// target alpha compositing mode.
391fn blend_color(color: vec4<f32>, alpha_factor: f32) -> vec4<f32> {
392    let alpha = color.a * alpha_factor;
393    let multiplier = select(1.0, alpha, globals.premultiplied_alpha != 0u);
394    return vec4<f32>(color.rgb * multiplier, alpha);
395}
396
397
398struct GradientColor {
399    solid: vec4<f32>,
400    color0: vec4<f32>,
401    color1: vec4<f32>,
402}
403
404fn prepare_gradient_color(tag: u32, color_space: u32,
405    solid: Hsla, colors: array<LinearColorStop, 2>) -> GradientColor {
406    var result = GradientColor();
407
408    if (tag == 0u || tag == 2u || tag == 3u) {
409        result.solid = hsla_to_rgba(solid);
410    } else if (tag == 1u) {
411        // The hsla_to_rgba is returns a linear sRGB color
412        result.color0 = hsla_to_rgba(colors[0].color);
413        result.color1 = hsla_to_rgba(colors[1].color);
414
415        // Prepare color space in vertex for avoid conversion
416        // in fragment shader for performance reasons
417        if (color_space == 0u) {
418            // sRGB
419            result.color0 = linear_to_srgba(result.color0);
420            result.color1 = linear_to_srgba(result.color1);
421        } else if (color_space == 1u) {
422            // Oklab
423            result.color0 = linear_srgb_to_oklab(result.color0);
424            result.color1 = linear_srgb_to_oklab(result.color1);
425        }
426    }
427
428    return result;
429}
430
431fn gradient_color(background: Background, position: vec2<f32>, bounds: Bounds,
432    solid_color: vec4<f32>, color0: vec4<f32>, color1: vec4<f32>) -> vec4<f32> {
433    var background_color = vec4<f32>(0.0);
434
435    switch (background.tag) {
436        default: {
437            return solid_color;
438        }
439        case 1u: {
440            // Linear gradient background.
441            // -90 degrees to match the CSS gradient angle.
442            let angle = background.gradient_angle_or_pattern_height;
443            let radians = (angle % 360.0 - 90.0) * M_PI_F / 180.0;
444            var direction = vec2<f32>(cos(radians), sin(radians));
445            let stop0_percentage = background.colors[0].percentage;
446            let stop1_percentage = background.colors[1].percentage;
447
448            // Expand the short side to be the same as the long side
449            if (bounds.size.x > bounds.size.y) {
450                direction.y *= bounds.size.y / bounds.size.x;
451            } else {
452                direction.x *= bounds.size.x / bounds.size.y;
453            }
454
455            // Get the t value for the linear gradient with the color stop percentages.
456            let half_size = bounds.size / 2.0;
457            let center = bounds.origin + half_size;
458            let center_to_point = position - center;
459            var t = dot(center_to_point, direction) / length(direction);
460            // Check the direct to determine the use x or y
461            if (abs(direction.x) > abs(direction.y)) {
462                t = (t + half_size.x) / bounds.size.x;
463            } else {
464                t = (t + half_size.y) / bounds.size.y;
465            }
466
467            // Adjust t based on the stop percentages
468            t = (t - stop0_percentage) / (stop1_percentage - stop0_percentage);
469            t = clamp(t, 0.0, 1.0);
470
471            switch (background.color_space) {
472                default: {
473                    background_color = srgba_to_linear(mix(color0, color1, t));
474                }
475                case 1u: {
476                    let oklab_color = mix(color0, color1, t);
477                    background_color = oklab_to_linear_srgb(oklab_color);
478                }
479            }
480        }
481        case 2u: {
482            // pattern slash
483            let gradient_angle_or_pattern_height = background.gradient_angle_or_pattern_height;
484            let pattern_width = (gradient_angle_or_pattern_height / 65535.0f) / 255.0f;
485            let pattern_interval = (gradient_angle_or_pattern_height % 65535.0f) / 255.0f;
486            let pattern_height = pattern_width + pattern_interval;
487            let stripe_angle = M_PI_F / 4.0;
488            let pattern_period = pattern_height * sin(stripe_angle);
489            let rotation = mat2x2<f32>(
490                cos(stripe_angle), -sin(stripe_angle),
491                sin(stripe_angle), cos(stripe_angle)
492            );
493            let relative_position = position - bounds.origin;
494            let rotated_point = rotation * relative_position;
495            let pattern = rotated_point.x % pattern_period;
496            let distance = min(pattern, pattern_period - pattern) - pattern_period * (pattern_width / pattern_height) /  2.0f;
497            background_color = solid_color;
498            background_color.a *= saturate(0.5 - distance);
499        }
500        case 3u: {
501            // checkerboard
502            let size = background.gradient_angle_or_pattern_height;
503            let relative_position = position - bounds.origin;
504
505            let x_index = floor(relative_position.x / size);
506            let y_index = floor(relative_position.y / size);
507            let should_be_colored = (x_index + y_index) % 2.0;
508
509            background_color = solid_color;
510            background_color.a *= saturate(should_be_colored);
511        }
512    }
513
514    return background_color;
515}
516
517// --- quads --- //
518
519struct Quad {
520    order: u32,
521    border_style: u32,
522    bounds: Bounds,
523    content_mask: Bounds,
524    background: Background,
525    border_color: Hsla,
526    corner_radii: Corners,
527    border_widths: Edges,
528}
529@group(1) @binding(0) var<storage, read> b_quads: array<Quad>;
530
531struct QuadVarying {
532    @builtin(position) position: vec4<f32>,
533    @location(0) @interpolate(flat) border_color: vec4<f32>,
534    @location(1) @interpolate(flat) quad_id: u32,
535    // TODO: use `clip_distance` once Naga supports it
536    @location(2) clip_distances: vec4<f32>,
537    @location(3) @interpolate(flat) background_solid: vec4<f32>,
538    @location(4) @interpolate(flat) background_color0: vec4<f32>,
539    @location(5) @interpolate(flat) background_color1: vec4<f32>,
540}
541
542@vertex
543fn vs_quad(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> QuadVarying {
544    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
545    let quad = b_quads[instance_id];
546
547    var out = QuadVarying();
548    out.position = to_device_position(unit_vertex, quad.bounds);
549
550    let gradient = prepare_gradient_color(
551        quad.background.tag,
552        quad.background.color_space,
553        quad.background.solid,
554        quad.background.colors
555    );
556    out.background_solid = gradient.solid;
557    out.background_color0 = gradient.color0;
558    out.background_color1 = gradient.color1;
559    out.border_color = hsla_to_rgba(quad.border_color);
560    out.quad_id = instance_id;
561    out.clip_distances = distance_from_clip_rect(unit_vertex, quad.bounds, quad.content_mask);
562    return out;
563}
564
565@fragment
566fn fs_quad(input: QuadVarying) -> @location(0) vec4<f32> {
567    // Alpha clip first, since we don't have `clip_distance`.
568    if (any(input.clip_distances < vec4<f32>(0.0))) {
569        return vec4<f32>(0.0);
570    }
571
572    let quad = b_quads[input.quad_id];
573
574    let background_color = gradient_color(quad.background, input.position.xy, quad.bounds,
575        input.background_solid, input.background_color0, input.background_color1);
576
577    let unrounded = quad.corner_radii.top_left == 0.0 &&
578        quad.corner_radii.bottom_left == 0.0 &&
579        quad.corner_radii.top_right == 0.0 &&
580        quad.corner_radii.bottom_right == 0.0;
581
582    // Fast path when the quad is not rounded and doesn't have any border
583    if (quad.border_widths.top == 0.0 &&
584            quad.border_widths.left == 0.0 &&
585            quad.border_widths.right == 0.0 &&
586            quad.border_widths.bottom == 0.0 &&
587            unrounded) {
588        return blend_color(background_color, 1.0);
589    }
590
591    let size = quad.bounds.size;
592    let half_size = size / 2.0;
593    let point = input.position.xy - quad.bounds.origin;
594    let center_to_point = point - half_size;
595
596    // Signed distance field threshold for inclusion of pixels. 0.5 is the
597    // minimum distance between the center of the pixel and the edge.
598    let antialias_threshold = 0.5;
599
600    // Radius of the nearest corner
601    let corner_radius = pick_corner_radius(center_to_point, quad.corner_radii);
602
603    // Width of the nearest borders
604    let border = vec2<f32>(
605        select(
606            quad.border_widths.right,
607            quad.border_widths.left,
608            center_to_point.x < 0.0),
609        select(
610            quad.border_widths.bottom,
611            quad.border_widths.top,
612            center_to_point.y < 0.0));
613
614    // 0-width borders are reduced so that `inner_sdf >= antialias_threshold`.
615    // The purpose of this is to not draw antialiasing pixels in this case.
616    let reduced_border =
617        vec2<f32>(select(border.x, -antialias_threshold, border.x == 0.0),
618                  select(border.y, -antialias_threshold, border.y == 0.0));
619
620    // Vector from the corner of the quad bounds to the point, after mirroring
621    // the point into the bottom right quadrant. Both components are <= 0.
622    let corner_to_point = abs(center_to_point) - half_size;
623
624    // Vector from the point to the center of the rounded corner's circle, also
625    // mirrored into bottom right quadrant.
626    let corner_center_to_point = corner_to_point + corner_radius;
627
628    // Whether the nearest point on the border is rounded
629    let is_near_rounded_corner =
630            corner_center_to_point.x >= 0 &&
631            corner_center_to_point.y >= 0;
632
633    // Vector from straight border inner corner to point.
634    let straight_border_inner_corner_to_point = corner_to_point + reduced_border;
635
636    // Whether the point is beyond the inner edge of the straight border.
637    let is_beyond_inner_straight_border =
638            straight_border_inner_corner_to_point.x > 0 ||
639            straight_border_inner_corner_to_point.y > 0;
640
641    // Whether the point is far enough inside the quad, such that the pixels are
642    // not affected by the straight border.
643    let is_within_inner_straight_border =
644        straight_border_inner_corner_to_point.x < -antialias_threshold &&
645        straight_border_inner_corner_to_point.y < -antialias_threshold;
646
647    // Fast path for points that must be part of the background.
648    //
649    // This could be optimized further for large rounded corners by including
650    // points in an inscribed rectangle, or some other quick linear check.
651    // However, that might negatively impact performance in the case of
652    // reasonable sizes for rounded corners.
653    if (is_within_inner_straight_border && !is_near_rounded_corner) {
654        return blend_color(background_color, 1.0);
655    }
656
657    // Signed distance of the point to the outside edge of the quad's border. It
658    // is positive outside this edge, and negative inside.
659    let outer_sdf = quad_sdf_impl(corner_center_to_point, corner_radius);
660
661    // Approximate signed distance of the point to the inside edge of the quad's
662    // border. It is negative outside this edge (within the border), and
663    // positive inside.
664    //
665    // This is not always an accurate signed distance:
666    // * The rounded portions with varying border width use an approximation of
667    //   nearest-point-on-ellipse.
668    // * When it is quickly known to be outside the edge, -1.0 is used.
669    var inner_sdf = 0.0;
670    if (corner_center_to_point.x <= 0 || corner_center_to_point.y <= 0) {
671        // Fast paths for straight borders.
672        inner_sdf = -max(straight_border_inner_corner_to_point.x,
673                         straight_border_inner_corner_to_point.y);
674    } else if (is_beyond_inner_straight_border) {
675        // Fast path for points that must be outside the inner edge.
676        inner_sdf = -1.0;
677    } else if (reduced_border.x == reduced_border.y) {
678        // Fast path for circular inner edge.
679        inner_sdf = -(outer_sdf + reduced_border.x);
680    } else {
681        let ellipse_radii = max(vec2<f32>(0.0), corner_radius - reduced_border);
682        inner_sdf = quarter_ellipse_sdf(corner_center_to_point, ellipse_radii);
683    }
684
685    // Negative when inside the border
686    let border_sdf = max(inner_sdf, outer_sdf);
687
688    var color = background_color;
689    if (border_sdf < antialias_threshold) {
690        var border_color = input.border_color;
691
692        // Dashed border logic when border_style == 1
693        if (quad.border_style == 1) {
694            // Position along the perimeter in "dash space", where each dash
695            // period has length 1
696            var t = 0.0;
697
698            // Total number of dash periods, so that the dash spacing can be
699            // adjusted to evenly divide it
700            var max_t = 0.0;
701
702            // Border width is proportional to dash size. This is the behavior
703            // used by browsers, but also avoids dashes from different segments
704            // overlapping when dash size is smaller than the border width.
705            //
706            // Dash pattern: (2 * border width) dash, (1 * border width) gap
707            let dash_length_per_width = 2.0;
708            let dash_gap_per_width = 1.0;
709            let dash_period_per_width = dash_length_per_width + dash_gap_per_width;
710
711            // Since the dash size is determined by border width, the density of
712            // dashes varies. Multiplying a pixel distance by this returns a
713            // position in dash space - it has units (dash period / pixels). So
714            // a dash velocity of (1 / 10) is 1 dash every 10 pixels.
715            var dash_velocity = 0.0;
716
717            // Dividing this by the border width gives the dash velocity
718            let dv_numerator = 1.0 / dash_period_per_width;
719
720            if (unrounded) {
721                // When corners aren't rounded, the dashes are separately laid
722                // out on each straight line, rather than around the whole
723                // perimeter. This way each line starts and ends with a dash.
724                let is_horizontal =
725                        corner_center_to_point.x <
726                        corner_center_to_point.y;
727
728                // When applying dashed borders to just some, not all, the sides.
729                // The way we chose border widths above sometimes comes with a 0 width value.
730                // So we choose again to avoid division by zero.
731                // TODO: A better solution exists taking a look at the whole file.
732                // this does not fix single dashed borders at the corners
733                let dashed_border = vec2<f32>(
734                        max(
735                            quad.border_widths.bottom,
736                            quad.border_widths.top,
737                        ),
738                        max(
739                            quad.border_widths.right,
740                            quad.border_widths.left,
741                        )
742                   );
743
744                let border_width = select(dashed_border.y, dashed_border.x, is_horizontal);
745                dash_velocity = dv_numerator / border_width;
746                t = select(point.y, point.x, is_horizontal) * dash_velocity;
747                max_t = select(size.y, size.x, is_horizontal) * dash_velocity;
748            } else {
749                // When corners are rounded, the dashes are laid out clockwise
750                // around the whole perimeter.
751
752                let r_tr = quad.corner_radii.top_right;
753                let r_br = quad.corner_radii.bottom_right;
754                let r_bl = quad.corner_radii.bottom_left;
755                let r_tl = quad.corner_radii.top_left;
756
757                let w_t = quad.border_widths.top;
758                let w_r = quad.border_widths.right;
759                let w_b = quad.border_widths.bottom;
760                let w_l = quad.border_widths.left;
761
762                // Straight side dash velocities
763                let dv_t = select(dv_numerator / w_t, 0.0, w_t <= 0.0);
764                let dv_r = select(dv_numerator / w_r, 0.0, w_r <= 0.0);
765                let dv_b = select(dv_numerator / w_b, 0.0, w_b <= 0.0);
766                let dv_l = select(dv_numerator / w_l, 0.0, w_l <= 0.0);
767
768                // Straight side lengths in dash space
769                let s_t = (size.x - r_tl - r_tr) * dv_t;
770                let s_r = (size.y - r_tr - r_br) * dv_r;
771                let s_b = (size.x - r_br - r_bl) * dv_b;
772                let s_l = (size.y - r_bl - r_tl) * dv_l;
773
774                let corner_dash_velocity_tr = corner_dash_velocity(dv_t, dv_r);
775                let corner_dash_velocity_br = corner_dash_velocity(dv_b, dv_r);
776                let corner_dash_velocity_bl = corner_dash_velocity(dv_b, dv_l);
777                let corner_dash_velocity_tl = corner_dash_velocity(dv_t, dv_l);
778
779                // Corner lengths in dash space
780                let c_tr = r_tr * (M_PI_F / 2.0) * corner_dash_velocity_tr;
781                let c_br = r_br * (M_PI_F / 2.0) * corner_dash_velocity_br;
782                let c_bl = r_bl * (M_PI_F / 2.0) * corner_dash_velocity_bl;
783                let c_tl = r_tl * (M_PI_F / 2.0) * corner_dash_velocity_tl;
784
785                // Cumulative dash space upto each segment
786                let upto_tr = s_t;
787                let upto_r = upto_tr + c_tr;
788                let upto_br = upto_r + s_r;
789                let upto_b = upto_br + c_br;
790                let upto_bl = upto_b + s_b;
791                let upto_l = upto_bl + c_bl;
792                let upto_tl = upto_l + s_l;
793                max_t = upto_tl + c_tl;
794
795                if (is_near_rounded_corner) {
796                    let radians = atan2(corner_center_to_point.y,
797                                        corner_center_to_point.x);
798                    let corner_t = radians * corner_radius;
799
800                    if (center_to_point.x >= 0.0) {
801                        if (center_to_point.y < 0.0) {
802                            dash_velocity = corner_dash_velocity_tr;
803                            // Subtracted because radians is pi/2 to 0 when
804                            // going clockwise around the top right corner,
805                            // since the y axis has been flipped
806                            t = upto_r - corner_t * dash_velocity;
807                        } else {
808                            dash_velocity = corner_dash_velocity_br;
809                            // Added because radians is 0 to pi/2 when going
810                            // clockwise around the bottom-right corner
811                            t = upto_br + corner_t * dash_velocity;
812                        }
813                    } else {
814                        if (center_to_point.y >= 0.0) {
815                            dash_velocity = corner_dash_velocity_bl;
816                            // Subtracted because radians is pi/2 to 0 when
817                            // going clockwise around the bottom-left corner,
818                            // since the x axis has been flipped
819                            t = upto_l - corner_t * dash_velocity;
820                        } else {
821                            dash_velocity = corner_dash_velocity_tl;
822                            // Added because radians is 0 to pi/2 when going
823                            // clockwise around the top-left corner, since both
824                            // axis were flipped
825                            t = upto_tl + corner_t * dash_velocity;
826                        }
827                    }
828                } else {
829                    // Straight borders
830                    let is_horizontal =
831                            corner_center_to_point.x <
832                            corner_center_to_point.y;
833                    if (is_horizontal) {
834                        if (center_to_point.y < 0.0) {
835                            dash_velocity = dv_t;
836                            t = (point.x - r_tl) * dash_velocity;
837                        } else {
838                            dash_velocity = dv_b;
839                            t = upto_bl - (point.x - r_bl) * dash_velocity;
840                        }
841                    } else {
842                        if (center_to_point.x < 0.0) {
843                            dash_velocity = dv_l;
844                            t = upto_tl - (point.y - r_tl) * dash_velocity;
845                        } else {
846                            dash_velocity = dv_r;
847                            t = upto_r + (point.y - r_tr) * dash_velocity;
848                        }
849                    }
850                }
851            }
852
853            let dash_length = dash_length_per_width / dash_period_per_width;
854            let desired_dash_gap = dash_gap_per_width / dash_period_per_width;
855
856            // Straight borders should start and end with a dash, so max_t is
857            // reduced to cause this.
858            max_t -= select(0.0, dash_length, unrounded);
859            if (max_t >= 1.0) {
860                // Adjust dash gap to evenly divide max_t.
861                let dash_count = floor(max_t);
862                let dash_period = max_t / dash_count;
863                border_color.a *= dash_alpha(
864                    t,
865                    dash_period,
866                    dash_length,
867                    dash_velocity,
868                    antialias_threshold);
869            } else if (unrounded) {
870                // When there isn't enough space for the full gap between the
871                // two start / end dashes of a straight border, reduce gap to
872                // make them fit.
873                let dash_gap = max_t - dash_length;
874                if (dash_gap > 0.0) {
875                    let dash_period = dash_length + dash_gap;
876                    border_color.a *= dash_alpha(
877                        t,
878                        dash_period,
879                        dash_length,
880                        dash_velocity,
881                        antialias_threshold);
882                }
883            }
884        }
885
886        // Blend the border on top of the background and then linearly interpolate
887        // between the two as we slide inside the background.
888        let blended_border = over(background_color, border_color);
889        color = mix(background_color, blended_border,
890                    saturate(antialias_threshold - inner_sdf));
891    }
892
893    return blend_color(color, saturate(antialias_threshold - outer_sdf));
894}
895
896// Returns the dash velocity of a corner given the dash velocity of the two
897// sides, by returning the slower velocity (larger dashes).
898//
899// Since 0 is used for dash velocity when the border width is 0 (instead of
900// +inf), this returns the other dash velocity in that case.
901//
902// An alternative to this might be to appropriately interpolate the dash
903// velocity around the corner, but that seems overcomplicated.
904fn corner_dash_velocity(dv1: f32, dv2: f32) -> f32 {
905    if (dv1 == 0.0) {
906        return dv2;
907    } else if (dv2 == 0.0) {
908        return dv1;
909    } else {
910        return min(dv1, dv2);
911    }
912}
913
914// Returns alpha used to render antialiased dashes.
915// `t` is within the dash when `fmod(t, period) < length`.
916fn dash_alpha(t: f32, period: f32, length: f32, dash_velocity: f32, antialias_threshold: f32) -> f32 {
917    let half_period = period / 2;
918    let half_length = length / 2;
919    // Value in [-half_period, half_period].
920    // The dash is in [-half_length, half_length].
921    let centered = fmod(t + half_period - half_length, period) - half_period;
922    // Signed distance for the dash, negative values are inside the dash.
923    let signed_distance = abs(centered) - half_length;
924    // Antialiased alpha based on the signed distance.
925    return saturate(antialias_threshold - signed_distance / dash_velocity);
926}
927
928// This approximates distance to the nearest point to a quarter ellipse in a way
929// that is sufficient for anti-aliasing when the ellipse is not very eccentric.
930// The components of `point` are expected to be positive.
931//
932// Negative on the outside and positive on the inside.
933fn quarter_ellipse_sdf(point: vec2<f32>, radii: vec2<f32>) -> f32 {
934    // Scale the space to treat the ellipse like a unit circle.
935    let circle_vec = point / radii;
936    let unit_circle_sdf = length(circle_vec) - 1.0;
937    // Approximate up-scaling of the length by using the average of the radii.
938    //
939    // TODO: A better solution would be to use the gradient of the implicit
940    // function for an ellipse to approximate a scaling factor.
941    return unit_circle_sdf * (radii.x + radii.y) * -0.5;
942}
943
944// Modulus that has the same sign as `a`.
945fn fmod(a: f32, b: f32) -> f32 {
946    return a - b * trunc(a / b);
947}
948
949// --- shadows --- //
950
951struct Shadow {
952    order: u32,
953    blur_radius: f32,
954    // The shadow rect for drop shadows; the "hole" rect for inset shadows.
955    bounds: Bounds,
956    corner_radii: Corners,
957    content_mask: Bounds,
958    color: Hsla,
959    // Only consulted when `inset == 1u`: the element's own bounds, used as a rounded-rect
960    // clip so the shadow never escapes the element.
961    element_bounds: Bounds,
962    element_corner_radii: Corners,
963    // 0 = drop shadow, 1 = inset shadow.
964    inset: u32,
965    pad: u32, // align to 8 bytes
966}
967@group(1) @binding(0) var<storage, read> b_shadows: array<Shadow>;
968
969struct ShadowVarying {
970    @builtin(position) position: vec4<f32>,
971    @location(0) @interpolate(flat) color: vec4<f32>,
972    @location(1) @interpolate(flat) shadow_id: u32,
973    //TODO: use `clip_distance` once Naga supports it
974    @location(3) clip_distances: vec4<f32>,
975}
976
977@vertex
978fn vs_shadow(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> ShadowVarying {
979    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
980    var shadow = b_shadows[instance_id];
981
982    var geometry: Bounds;
983    if (shadow.inset != 0u) {
984        geometry = shadow.element_bounds;
985    } else {
986        // Leave room for the gaussian tail outside the shadow rect.
987        let margin = 3.0 * shadow.blur_radius;
988        geometry = shadow.bounds;
989        geometry.origin -= vec2<f32>(margin);
990        geometry.size += 2.0 * vec2<f32>(margin);
991    }
992
993    var out = ShadowVarying();
994    out.position = to_device_position(unit_vertex, geometry);
995    out.color = hsla_to_rgba(shadow.color);
996    out.shadow_id = instance_id;
997    out.clip_distances = distance_from_clip_rect(unit_vertex, geometry, shadow.content_mask);
998    return out;
999}
1000
1001@fragment
1002fn fs_shadow(input: ShadowVarying) -> @location(0) vec4<f32> {
1003    // Alpha clip first, since we don't have `clip_distance`.
1004    if (any(input.clip_distances < vec4<f32>(0.0))) {
1005        return vec4<f32>(0.0);
1006    }
1007
1008    let shadow = b_shadows[input.shadow_id];
1009    let half_size = shadow.bounds.size / 2.0;
1010    let center = shadow.bounds.origin + half_size;
1011    let center_to_point = input.position.xy - center;
1012
1013    let corner_radius = pick_corner_radius(center_to_point, shadow.corner_radii);
1014
1015    var alpha: f32;
1016    if (shadow.blur_radius == 0.0) {
1017        let distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii);
1018        alpha = saturate(0.5 - distance);
1019    } else {
1020        // The signal is only non-zero in a limited range, so don't waste samples
1021        let low = center_to_point.y - half_size.y;
1022        let high = center_to_point.y + half_size.y;
1023        let start = clamp(-3.0 * shadow.blur_radius, low, high);
1024        let end = clamp(3.0 * shadow.blur_radius, low, high);
1025
1026        // Accumulate samples (we can get away with surprisingly few samples)
1027        let step = (end - start) / 4.0;
1028        var y = start + step * 0.5;
1029        alpha = 0.0;
1030        for (var i = 0; i < 4; i += 1) {
1031            let blur = blur_along_x(center_to_point.x, center_to_point.y - y,
1032                shadow.blur_radius, corner_radius, half_size);
1033            alpha +=  blur * gaussian(y, shadow.blur_radius) * step;
1034            y += step;
1035        }
1036    }
1037
1038    if (shadow.inset != 0u) {
1039        // The inset shadow is the complement of the (blurred) hole rect, clipped to the element.
1040        // `saturate(0.5 - d)` gives a 1-pixel antialiased edge: d <= -0.5 -> 1, d >= 0.5 -> 0.
1041        alpha = 1.0 - alpha;
1042        let element_distance = quad_sdf(input.position.xy, shadow.element_bounds,
1043                                        shadow.element_corner_radii);
1044        alpha *= saturate(0.5 - element_distance);
1045    }
1046
1047    return blend_color(input.color, alpha);
1048}
1049
1050// --- path rasterization --- //
1051
1052struct PathRasterizationVertex {
1053    xy_position: vec2<f32>,
1054    st_position: vec2<f32>,
1055    color: Background,
1056    bounds: Bounds,
1057}
1058
1059@group(1) @binding(0) var<storage, read> b_path_vertices: array<PathRasterizationVertex>;
1060
1061struct PathRasterizationVarying {
1062    @builtin(position) position: vec4<f32>,
1063    @location(0) st_position: vec2<f32>,
1064    @location(1) @interpolate(flat) vertex_id: u32,
1065    //TODO: use `clip_distance` once Naga supports it
1066    @location(3) clip_distances: vec4<f32>,
1067}
1068
1069@vertex
1070fn vs_path_rasterization(@builtin(vertex_index) vertex_id: u32) -> PathRasterizationVarying {
1071    let v = b_path_vertices[vertex_id];
1072
1073    var out = PathRasterizationVarying();
1074    out.position = to_device_position_impl(v.xy_position);
1075    out.st_position = v.st_position;
1076    out.vertex_id = vertex_id;
1077    out.clip_distances = distance_from_clip_rect_impl(v.xy_position, v.bounds);
1078    return out;
1079}
1080
1081@fragment
1082fn fs_path_rasterization(input: PathRasterizationVarying) -> @location(0) vec4<f32> {
1083    let dx = dpdx(input.st_position);
1084    let dy = dpdy(input.st_position);
1085    if (any(input.clip_distances < vec4<f32>(0.0))) {
1086        return vec4<f32>(0.0);
1087    }
1088
1089    let v = b_path_vertices[input.vertex_id];
1090    let background = v.color;
1091    let bounds = v.bounds;
1092
1093    var alpha: f32;
1094    if (length(vec2<f32>(dx.x, dy.x)) < 0.001) {
1095        // If the gradient is too small, return a solid color.
1096        alpha = 1.0;
1097    } else {
1098        let gradient = 2.0 * input.st_position.xx * vec2<f32>(dx.x, dy.x) - vec2<f32>(dx.y, dy.y);
1099        let f = input.st_position.x * input.st_position.x - input.st_position.y;
1100        let distance = f / length(gradient);
1101        alpha = saturate(0.5 - distance);
1102    }
1103    let prepared_gradient = prepare_gradient_color(
1104        background.tag,
1105        background.color_space,
1106        background.solid,
1107        background.colors,
1108    );
1109    let color = gradient_color(background, input.position.xy, bounds,
1110        prepared_gradient.solid, prepared_gradient.color0, prepared_gradient.color1);
1111    return vec4<f32>(color.rgb * color.a * alpha, color.a * alpha);
1112}
1113
1114// --- paths --- //
1115
1116struct PathSprite {
1117    bounds: Bounds,
1118}
1119@group(1) @binding(0) var<storage, read> b_path_sprites: array<PathSprite>;
1120
1121struct PathVarying {
1122    @builtin(position) position: vec4<f32>,
1123    @location(0) texture_coords: vec2<f32>,
1124}
1125
1126@vertex
1127fn vs_path(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PathVarying {
1128    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
1129    let sprite = b_path_sprites[instance_id];
1130    // Don't apply content mask because it was already accounted for when rasterizing the path.
1131    let device_position = to_device_position(unit_vertex, sprite.bounds);
1132    // For screen-space intermediate texture, convert screen position to texture coordinates
1133    let screen_position = sprite.bounds.origin + unit_vertex * sprite.bounds.size;
1134    let texture_coords = screen_position / globals.viewport_size;
1135
1136    var out = PathVarying();
1137    out.position = device_position;
1138    out.texture_coords = texture_coords;
1139
1140    return out;
1141}
1142
1143@fragment
1144fn fs_path(input: PathVarying) -> @location(0) vec4<f32> {
1145    let sample = textureSample(t_sprite, s_sprite, input.texture_coords);
1146    return sample;
1147}
1148
1149// --- underlines --- //
1150
1151struct Underline {
1152    order: u32,
1153    pad: u32,
1154    bounds: Bounds,
1155    content_mask: Bounds,
1156    color: Hsla,
1157    thickness: f32,
1158    wavy: u32,
1159}
1160@group(1) @binding(0) var<storage, read> b_underlines: array<Underline>;
1161
1162struct UnderlineVarying {
1163    @builtin(position) position: vec4<f32>,
1164    @location(0) @interpolate(flat) color: vec4<f32>,
1165    @location(1) @interpolate(flat) underline_id: u32,
1166    //TODO: use `clip_distance` once Naga supports it
1167    @location(3) clip_distances: vec4<f32>,
1168}
1169
1170@vertex
1171fn vs_underline(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> UnderlineVarying {
1172    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
1173    let underline = b_underlines[instance_id];
1174
1175    var out = UnderlineVarying();
1176    out.position = to_device_position(unit_vertex, underline.bounds);
1177    out.color = hsla_to_rgba(underline.color);
1178    out.underline_id = instance_id;
1179    out.clip_distances = distance_from_clip_rect(unit_vertex, underline.bounds, underline.content_mask);
1180    return out;
1181}
1182
1183@fragment
1184fn fs_underline(input: UnderlineVarying) -> @location(0) vec4<f32> {
1185    const WAVE_FREQUENCY: f32 = 2.0;
1186    const WAVE_HEIGHT_RATIO: f32 = 0.8;
1187
1188    // Alpha clip first, since we don't have `clip_distance`.
1189    if (any(input.clip_distances < vec4<f32>(0.0))) {
1190        return vec4<f32>(0.0);
1191    }
1192
1193    let underline = b_underlines[input.underline_id];
1194    if (underline.wavy == 0u)
1195    {
1196        return blend_color(input.color, input.color.a);
1197    }
1198
1199    let half_thickness = underline.thickness * 0.5;
1200
1201    let st = (input.position.xy - underline.bounds.origin) / underline.bounds.size.y - vec2<f32>(0.0, 0.5);
1202    let frequency = M_PI_F * WAVE_FREQUENCY * underline.thickness / underline.bounds.size.y;
1203    let amplitude = (underline.thickness * WAVE_HEIGHT_RATIO) / underline.bounds.size.y;
1204
1205    let sine = sin(st.x * frequency) * amplitude;
1206    let dSine = cos(st.x * frequency) * amplitude * frequency;
1207    let distance = (st.y - sine) / sqrt(1.0 + dSine * dSine);
1208    let distance_in_pixels = distance * underline.bounds.size.y;
1209    let distance_from_top_border = distance_in_pixels - half_thickness;
1210    let distance_from_bottom_border = distance_in_pixels + half_thickness;
1211    let alpha = saturate(0.5 - max(-distance_from_bottom_border, distance_from_top_border));
1212    return blend_color(input.color, alpha * input.color.a);
1213}
1214
1215// --- monochrome sprites --- //
1216
1217struct MonochromeSprite {
1218    order: u32,
1219    pad: u32,
1220    bounds: Bounds,
1221    content_mask: Bounds,
1222    color: Hsla,
1223    tile: AtlasTile,
1224    transformation: TransformationMatrix,
1225}
1226@group(1) @binding(0) var<storage, read> b_mono_sprites: array<MonochromeSprite>;
1227
1228struct MonoSpriteVarying {
1229    @builtin(position) position: vec4<f32>,
1230    @location(0) tile_position: vec2<f32>,
1231    @location(1) @interpolate(flat) color: vec4<f32>,
1232    @location(3) clip_distances: vec4<f32>,
1233}
1234
1235@vertex
1236fn vs_mono_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> MonoSpriteVarying {
1237    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
1238    let sprite = b_mono_sprites[instance_id];
1239
1240    var out = MonoSpriteVarying();
1241    out.position = to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation);
1242
1243    out.tile_position = to_tile_position(unit_vertex, sprite.tile);
1244    out.color = hsla_to_rgba(sprite.color);
1245    out.clip_distances = distance_from_clip_rect_transformed(unit_vertex, sprite.bounds, sprite.content_mask, sprite.transformation);
1246    return out;
1247}
1248
1249@fragment
1250fn fs_mono_sprite(input: MonoSpriteVarying) -> @location(0) vec4<f32> {
1251    let sample = textureSample(t_sprite, s_sprite, input.tile_position).r;
1252    let alpha_corrected = apply_contrast_and_gamma_correction(sample, input.color.rgb, gamma_params.grayscale_enhanced_contrast, gamma_params.gamma_ratios);
1253
1254    // Alpha clip after using the derivatives.
1255    if (any(input.clip_distances < vec4<f32>(0.0))) {
1256        return vec4<f32>(0.0);
1257    }
1258
1259    return blend_color(input.color, alpha_corrected);
1260}
1261
1262// --- polychrome sprites --- //
1263
1264struct PolychromeSprite {
1265    order: u32,
1266    pad: u32,
1267    grayscale: u32,
1268    opacity: f32,
1269    bounds: Bounds,
1270    content_mask: Bounds,
1271    corner_radii: Corners,
1272    tile: AtlasTile,
1273}
1274@group(1) @binding(0) var<storage, read> b_poly_sprites: array<PolychromeSprite>;
1275
1276struct PolySpriteVarying {
1277    @builtin(position) position: vec4<f32>,
1278    @location(0) tile_position: vec2<f32>,
1279    @location(1) @interpolate(flat) sprite_id: u32,
1280    @location(3) clip_distances: vec4<f32>,
1281}
1282
1283@vertex
1284fn vs_poly_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PolySpriteVarying {
1285    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
1286    let sprite = b_poly_sprites[instance_id];
1287
1288    var out = PolySpriteVarying();
1289    out.position = to_device_position(unit_vertex, sprite.bounds);
1290    out.tile_position = to_tile_position(unit_vertex, sprite.tile);
1291    out.sprite_id = instance_id;
1292    out.clip_distances = distance_from_clip_rect(unit_vertex, sprite.bounds, sprite.content_mask);
1293    return out;
1294}
1295
1296@fragment
1297fn fs_poly_sprite(input: PolySpriteVarying) -> @location(0) vec4<f32> {
1298    let sample = textureSample(t_sprite, s_sprite, input.tile_position);
1299    // Alpha clip after using the derivatives.
1300    if (any(input.clip_distances < vec4<f32>(0.0))) {
1301        return vec4<f32>(0.0);
1302    }
1303
1304    let sprite = b_poly_sprites[input.sprite_id];
1305    let distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii);
1306
1307    var color = sample;
1308    if (sprite.grayscale != 0u) {
1309        let grayscale = dot(color.rgb, GRAYSCALE_FACTORS);
1310        color = vec4<f32>(vec3<f32>(grayscale), sample.a);
1311    }
1312    return blend_color(color, sprite.opacity * saturate(0.5 - distance));
1313}
1314
1315// --- surfaces --- //
1316
1317struct SurfaceParams {
1318    bounds: Bounds,
1319    content_mask: Bounds,
1320}
1321
1322@group(1) @binding(0) var<uniform> surface_locals: SurfaceParams;
1323@group(1) @binding(1) var t_y: texture_2d<f32>;
1324@group(1) @binding(2) var t_cb_cr: texture_2d<f32>;
1325@group(1) @binding(3) var s_surface: sampler;
1326
1327const ycbcr_to_RGB = mat4x4<f32>(
1328    vec4<f32>( 1.0000f,  1.0000f,  1.0000f, 0.0),
1329    vec4<f32>( 0.0000f, -0.3441f,  1.7720f, 0.0),
1330    vec4<f32>( 1.4020f, -0.7141f,  0.0000f, 0.0),
1331    vec4<f32>(-0.7010f,  0.5291f, -0.8860f, 1.0),
1332);
1333
1334struct SurfaceVarying {
1335    @builtin(position) position: vec4<f32>,
1336    @location(0) texture_position: vec2<f32>,
1337    @location(3) clip_distances: vec4<f32>,
1338}
1339
1340@vertex
1341fn vs_surface(@builtin(vertex_index) vertex_id: u32) -> SurfaceVarying {
1342    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
1343
1344    var out = SurfaceVarying();
1345    out.position = to_device_position(unit_vertex, surface_locals.bounds);
1346    out.texture_position = unit_vertex;
1347    out.clip_distances = distance_from_clip_rect(unit_vertex, surface_locals.bounds, surface_locals.content_mask);
1348    return out;
1349}
1350
1351@fragment
1352fn fs_surface(input: SurfaceVarying) -> @location(0) vec4<f32> {
1353    // Alpha clip after using the derivatives.
1354    if (any(input.clip_distances < vec4<f32>(0.0))) {
1355        return vec4<f32>(0.0);
1356    }
1357
1358    let y_cb_cr = vec4<f32>(
1359        textureSampleLevel(t_y, s_surface, input.texture_position, 0.0).r,
1360        textureSampleLevel(t_cb_cr, s_surface, input.texture_position, 0.0).rg,
1361        1.0);
1362
1363    return ycbcr_to_RGB * y_cb_cr;
1364}
1365
Served at tenant.openagents/omega Member data and write actions are omitted.