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