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