shaders.wgsl

  1struct GlobalParams {
  2    viewport_size: vec2<f32>,
  3    premultiplied_alpha: u32,
  4    pad: u32,
  5}
  6
  7var<uniform> globals: GlobalParams;
  8var t_sprite: texture_2d<f32>;
  9var s_sprite: sampler;
 10
 11const M_PI_F: f32 = 3.1415926;
 12const GRAYSCALE_FACTORS: vec3<f32> = vec3<f32>(0.2126, 0.7152, 0.0722);
 13
 14struct Bounds {
 15    origin: vec2<f32>,
 16    size: vec2<f32>,
 17}
 18
 19struct Corners {
 20    top_left: f32,
 21    top_right: f32,
 22    bottom_right: f32,
 23    bottom_left: f32,
 24}
 25
 26struct Edges {
 27    top: f32,
 28    right: f32,
 29    bottom: f32,
 30    left: f32,
 31}
 32
 33struct Hsla {
 34    h: f32,
 35    s: f32,
 36    l: f32,
 37    a: f32,
 38}
 39
 40struct LinearColorStop {
 41    color: Hsla,
 42    percentage: f32,
 43}
 44
 45struct Background {
 46    // 0u is Solid
 47    // 1u is LinearGradient
 48    // 2u is PatternSlash
 49    tag: u32,
 50    // 0u is sRGB linear color
 51    // 1u is Oklab color
 52    color_space: u32,
 53    solid: Hsla,
 54    gradient_angle_or_pattern_height: f32,
 55    colors: array<LinearColorStop, 2>,
 56    pad: u32,
 57}
 58
 59struct AtlasTextureId {
 60    index: u32,
 61    kind: u32,
 62}
 63
 64struct AtlasBounds {
 65    origin: vec2<i32>,
 66    size: vec2<i32>,
 67}
 68
 69struct AtlasTile {
 70    texture_id: AtlasTextureId,
 71    tile_id: u32,
 72    padding: u32,
 73    bounds: AtlasBounds,
 74}
 75
 76struct TransformationMatrix {
 77    rotation_scale: mat2x2<f32>,
 78    translation: vec2<f32>,
 79}
 80
 81fn to_device_position_impl(position: vec2<f32>) -> vec4<f32> {
 82    let device_position = position / globals.viewport_size * vec2<f32>(2.0, -2.0) + vec2<f32>(-1.0, 1.0);
 83    return vec4<f32>(device_position, 0.0, 1.0);
 84}
 85
 86fn to_device_position(unit_vertex: vec2<f32>, bounds: Bounds) -> vec4<f32> {
 87    let position = unit_vertex * vec2<f32>(bounds.size) + bounds.origin;
 88    return to_device_position_impl(position);
 89}
 90
 91fn to_device_position_transformed(unit_vertex: vec2<f32>, bounds: Bounds, transform: TransformationMatrix) -> vec4<f32> {
 92    let position = unit_vertex * vec2<f32>(bounds.size) + bounds.origin;
 93    //Note: Rust side stores it as row-major, so transposing here
 94    let transformed = transpose(transform.rotation_scale) * position + transform.translation;
 95    return to_device_position_impl(transformed);
 96}
 97
 98fn to_tile_position(unit_vertex: vec2<f32>, tile: AtlasTile) -> vec2<f32> {
 99  let atlas_size = vec2<f32>(textureDimensions(t_sprite, 0));
100  return (vec2<f32>(tile.bounds.origin) + unit_vertex * vec2<f32>(tile.bounds.size)) / atlas_size;
101}
102
103fn distance_from_clip_rect_impl(position: vec2<f32>, clip_bounds: Bounds) -> vec4<f32> {
104    let tl = position - clip_bounds.origin;
105    let br = clip_bounds.origin + clip_bounds.size - position;
106    return vec4<f32>(tl.x, br.x, tl.y, br.y);
107}
108
109fn distance_from_clip_rect(unit_vertex: vec2<f32>, bounds: Bounds, clip_bounds: Bounds) -> vec4<f32> {
110    let position = unit_vertex * vec2<f32>(bounds.size) + bounds.origin;
111    return distance_from_clip_rect_impl(position, clip_bounds);
112}
113
114// https://gamedev.stackexchange.com/questions/92015/optimized-linear-to-srgb-glsl
115fn srgb_to_linear(srgb: vec3<f32>) -> vec3<f32> {
116    let cutoff = srgb < vec3<f32>(0.04045);
117    let higher = pow((srgb + vec3<f32>(0.055)) / vec3<f32>(1.055), vec3<f32>(2.4));
118    let lower = srgb / vec3<f32>(12.92);
119    return select(higher, lower, cutoff);
120}
121
122fn linear_to_srgb(linear: vec3<f32>) -> vec3<f32> {
123    let cutoff = linear < vec3<f32>(0.0031308);
124    let higher = vec3<f32>(1.055) * pow(linear, vec3<f32>(1.0 / 2.4)) - vec3<f32>(0.055);
125    let lower = linear * vec3<f32>(12.92);
126    return select(higher, lower, cutoff);
127}
128
129/// Convert a linear color to sRGBA space.
130fn linear_to_srgba(color: vec4<f32>) -> vec4<f32> {
131    return vec4<f32>(linear_to_srgb(color.rgb), color.a);
132}
133
134/// Convert a sRGBA color to linear space.
135fn srgba_to_linear(color: vec4<f32>) -> vec4<f32> {
136    return vec4<f32>(srgb_to_linear(color.rgb), color.a);
137}
138
139/// Hsla to linear RGBA conversion.
140fn hsla_to_rgba(hsla: Hsla) -> vec4<f32> {
141    let h = hsla.h * 6.0; // Now, it's an angle but scaled in [0, 6) range
142    let s = hsla.s;
143    let l = hsla.l;
144    let a = hsla.a;
145
146    let c = (1.0 - abs(2.0 * l - 1.0)) * s;
147    let x = c * (1.0 - abs(h % 2.0 - 1.0));
148    let m = l - c / 2.0;
149    var color = vec3<f32>(m);
150
151    if (h >= 0.0 && h < 1.0) {
152        color.r += c;
153        color.g += x;
154    } else if (h >= 1.0 && h < 2.0) {
155        color.r += x;
156        color.g += c;
157    } else if (h >= 2.0 && h < 3.0) {
158        color.g += c;
159        color.b += x;
160    } else if (h >= 3.0 && h < 4.0) {
161        color.g += x;
162        color.b += c;
163    } else if (h >= 4.0 && h < 5.0) {
164        color.r += x;
165        color.b += c;
166    } else {
167        color.r += c;
168        color.b += x;
169    }
170
171    // Input colors are assumed to be in sRGB space,
172    // but blending and rendering needs to happen in linear space.
173    // The output will be converted to sRGB by either the target
174    // texture format or the swapchain color space.
175    let linear = srgb_to_linear(color);
176    return vec4<f32>(linear, a);
177}
178
179/// Convert a linear sRGB to Oklab space.
180/// Reference: https://bottosson.github.io/posts/oklab/#converting-from-linear-srgb-to-oklab
181fn linear_srgb_to_oklab(color: vec4<f32>) -> vec4<f32> {
182	let l = 0.4122214708 * color.r + 0.5363325363 * color.g + 0.0514459929 * color.b;
183	let m = 0.2119034982 * color.r + 0.6806995451 * color.g + 0.1073969566 * color.b;
184	let s = 0.0883024619 * color.r + 0.2817188376 * color.g + 0.6299787005 * color.b;
185
186	let l_ = pow(l, 1.0 / 3.0);
187	let m_ = pow(m, 1.0 / 3.0);
188	let s_ = pow(s, 1.0 / 3.0);
189
190	return vec4<f32>(
191		0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
192		1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
193		0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
194		color.a
195	);
196}
197
198/// Convert an Oklab color to linear sRGB space.
199fn oklab_to_linear_srgb(color: vec4<f32>) -> vec4<f32> {
200	let l_ = color.r + 0.3963377774 * color.g + 0.2158037573 * color.b;
201	let m_ = color.r - 0.1055613458 * color.g - 0.0638541728 * color.b;
202	let s_ = color.r - 0.0894841775 * color.g - 1.2914855480 * color.b;
203
204	let l = l_ * l_ * l_;
205	let m = m_ * m_ * m_;
206	let s = s_ * s_ * s_;
207
208	return vec4<f32>(
209		4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
210		-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
211		-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s,
212		color.a
213	);
214}
215
216fn over(below: vec4<f32>, above: vec4<f32>) -> vec4<f32> {
217    let alpha = above.a + below.a * (1.0 - above.a);
218    let color = (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha;
219    return vec4<f32>(color, alpha);
220}
221
222// A standard gaussian function, used for weighting samples
223fn gaussian(x: f32, sigma: f32) -> f32{
224    return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * M_PI_F) * sigma);
225}
226
227// This approximates the error function, needed for the gaussian integral
228fn erf(v: vec2<f32>) -> vec2<f32> {
229    let s = sign(v);
230    let a = abs(v);
231    let r1 = 1.0 + (0.278393 + (0.230389 + (0.000972 + 0.078108 * a) * a) * a) * a;
232    let r2 = r1 * r1;
233    return s - s / (r2 * r2);
234}
235
236fn blur_along_x(x: f32, y: f32, sigma: f32, corner: f32, half_size: vec2<f32>) -> f32 {
237  let delta = min(half_size.y - corner - abs(y), 0.0);
238  let curved = half_size.x - corner + sqrt(max(0.0, corner * corner - delta * delta));
239  let integral = 0.5 + 0.5 * erf((x + vec2<f32>(-curved, curved)) * (sqrt(0.5) / sigma));
240  return integral.y - integral.x;
241}
242
243fn pick_corner_radius(point: vec2<f32>, radii: Corners) -> f32 {
244    if (point.x < 0.0) {
245        if (point.y < 0.0) {
246            return radii.top_left;
247        } else {
248            return radii.bottom_left;
249        }
250    } else {
251        if (point.y < 0.0) {
252            return radii.top_right;
253        } else {
254            return radii.bottom_right;
255        }
256    }
257}
258
259fn quad_sdf(point: vec2<f32>, bounds: Bounds, corner_radii: Corners) -> f32 {
260    let half_size = bounds.size / 2.0;
261    let center = bounds.origin + half_size;
262    let center_to_point = point - center;
263    let corner_radius = pick_corner_radius(center_to_point, corner_radii);
264    let rounded_edge_to_point = abs(center_to_point) - half_size + corner_radius;
265    return length(max(vec2<f32>(0.0), rounded_edge_to_point)) +
266        min(0.0, max(rounded_edge_to_point.x, rounded_edge_to_point.y)) -
267        corner_radius;
268}
269
270// Abstract away the final color transformation based on the
271// target alpha compositing mode.
272fn blend_color(color: vec4<f32>, alpha_factor: f32) -> vec4<f32> {
273    let alpha = color.a * alpha_factor;
274    let multiplier = select(1.0, alpha, globals.premultiplied_alpha != 0u);
275    return vec4<f32>(color.rgb * multiplier, alpha);
276}
277
278
279struct GradientColor {
280    solid: vec4<f32>,
281    color0: vec4<f32>,
282    color1: vec4<f32>,
283}
284
285fn prepare_gradient_color(tag: u32, color_space: u32,
286    solid: Hsla, colors: array<LinearColorStop, 2>) -> GradientColor {
287    var result = GradientColor();
288
289    if (tag == 0u || tag == 2u) {
290        result.solid = hsla_to_rgba(solid);
291    } else if (tag == 1u) {
292        // The hsla_to_rgba is returns a linear sRGB color
293        result.color0 = hsla_to_rgba(colors[0].color);
294        result.color1 = hsla_to_rgba(colors[1].color);
295
296        // Prepare color space in vertex for avoid conversion
297        // in fragment shader for performance reasons
298        if (color_space == 0u) {
299            // sRGB
300            result.color0 = linear_to_srgba(result.color0);
301            result.color1 = linear_to_srgba(result.color1);
302        } else if (color_space == 1u) {
303            // Oklab
304            result.color0 = linear_srgb_to_oklab(result.color0);
305            result.color1 = linear_srgb_to_oklab(result.color1);
306        }
307    }
308
309    return result;
310}
311
312fn gradient_color(background: Background, position: vec2<f32>, bounds: Bounds,
313    solid_color: vec4<f32>, color0: vec4<f32>, color1: vec4<f32>) -> vec4<f32> {
314    var background_color = vec4<f32>(0.0);
315
316    switch (background.tag) {
317        default: {
318            return solid_color;
319        }
320        case 1u: {
321            // Linear gradient background.
322            // -90 degrees to match the CSS gradient angle.
323            let angle = background.gradient_angle_or_pattern_height;
324            let radians = (angle % 360.0 - 90.0) * M_PI_F / 180.0;
325            var direction = vec2<f32>(cos(radians), sin(radians));
326            let stop0_percentage = background.colors[0].percentage;
327            let stop1_percentage = background.colors[1].percentage;
328
329            // Expand the short side to be the same as the long side
330            if (bounds.size.x > bounds.size.y) {
331                direction.y *= bounds.size.y / bounds.size.x;
332            } else {
333                direction.x *= bounds.size.x / bounds.size.y;
334            }
335
336            // Get the t value for the linear gradient with the color stop percentages.
337            let half_size = bounds.size / 2.0;
338            let center = bounds.origin + half_size;
339            let center_to_point = position - center;
340            var t = dot(center_to_point, direction) / length(direction);
341            // Check the direct to determine the use x or y
342            if (abs(direction.x) > abs(direction.y)) {
343                t = (t + half_size.x) / bounds.size.x;
344            } else {
345                t = (t + half_size.y) / bounds.size.y;
346            }
347
348            // Adjust t based on the stop percentages
349            t = (t - stop0_percentage) / (stop1_percentage - stop0_percentage);
350            t = clamp(t, 0.0, 1.0);
351
352            switch (background.color_space) {
353                default: {
354                    background_color = srgba_to_linear(mix(color0, color1, t));
355                }
356                case 1u: {
357                    let oklab_color = mix(color0, color1, t);
358                    background_color = oklab_to_linear_srgb(oklab_color);
359                }
360            }
361        }
362        case 2u: {
363            let gradient_angle_or_pattern_height = background.gradient_angle_or_pattern_height;
364            let pattern_width = (gradient_angle_or_pattern_height / 65535.0f) / 255.0f;
365            let pattern_interval = (gradient_angle_or_pattern_height % 65535.0f) / 255.0f;
366            let pattern_height = pattern_width + pattern_interval;
367            let stripe_angle = M_PI_F / 4.0;
368            let pattern_period = pattern_height * sin(stripe_angle);
369            let rotation = mat2x2<f32>(
370                cos(stripe_angle), -sin(stripe_angle),
371                sin(stripe_angle), cos(stripe_angle)
372            );
373            let relative_position = position - bounds.origin;
374            let rotated_point = rotation * relative_position;
375            let pattern = rotated_point.x % pattern_period;
376            let distance = min(pattern, pattern_period - pattern) - pattern_period * (pattern_width / pattern_height) /  2.0f;
377            background_color = solid_color;
378            background_color.a *= saturate(0.5 - distance);
379        }
380    }
381
382    return background_color;
383}
384
385// --- quads --- //
386
387struct Quad {
388    order: u32,
389    pad: u32,
390    bounds: Bounds,
391    content_mask: Bounds,
392    background: Background,
393    border_color: Hsla,
394    corner_radii: Corners,
395    border_widths: Edges,
396}
397var<storage, read> b_quads: array<Quad>;
398
399struct QuadVarying {
400    @builtin(position) position: vec4<f32>,
401    @location(0) @interpolate(flat) border_color: vec4<f32>,
402    @location(1) @interpolate(flat) quad_id: u32,
403    // TODO: use `clip_distance` once Naga supports it
404    @location(2) clip_distances: vec4<f32>,
405    @location(3) @interpolate(flat) background_solid: vec4<f32>,
406    @location(4) @interpolate(flat) background_color0: vec4<f32>,
407    @location(5) @interpolate(flat) background_color1: vec4<f32>,
408}
409
410@vertex
411fn vs_quad(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> QuadVarying {
412    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
413    let quad = b_quads[instance_id];
414
415    var out = QuadVarying();
416    out.position = to_device_position(unit_vertex, quad.bounds);
417
418    let gradient = prepare_gradient_color(
419        quad.background.tag,
420        quad.background.color_space,
421        quad.background.solid,
422        quad.background.colors
423    );
424    out.background_solid = gradient.solid;
425    out.background_color0 = gradient.color0;
426    out.background_color1 = gradient.color1;
427    out.border_color = hsla_to_rgba(quad.border_color);
428    out.quad_id = instance_id;
429    out.clip_distances = distance_from_clip_rect(unit_vertex, quad.bounds, quad.content_mask);
430    return out;
431}
432
433@fragment
434fn fs_quad(input: QuadVarying) -> @location(0) vec4<f32> {
435    // Alpha clip first, since we don't have `clip_distance`.
436    if (any(input.clip_distances < vec4<f32>(0.0))) {
437        return vec4<f32>(0.0);
438    }
439
440    let quad = b_quads[input.quad_id];
441    let half_size = quad.bounds.size / 2.0;
442    let center = quad.bounds.origin + half_size;
443    let center_to_point = input.position.xy - center;
444
445    let background_color = gradient_color(quad.background, input.position.xy, quad.bounds,
446        input.background_solid, input.background_color0, input.background_color1);
447
448    // Fast path when the quad is not rounded and doesn't have any border.
449    if (quad.corner_radii.top_left == 0.0 && quad.corner_radii.bottom_left == 0.0 &&
450        quad.corner_radii.top_right == 0.0 &&
451        quad.corner_radii.bottom_right == 0.0 && quad.border_widths.top == 0.0 &&
452        quad.border_widths.left == 0.0 && quad.border_widths.right == 0.0 &&
453        quad.border_widths.bottom == 0.0) {
454        return blend_color(background_color, 1.0);
455    }
456
457    let corner_radius = pick_corner_radius(center_to_point, quad.corner_radii);
458    let rounded_edge_to_point = abs(center_to_point) - half_size + corner_radius;
459    let distance =
460      length(max(vec2<f32>(0.0), rounded_edge_to_point)) +
461      min(0.0, max(rounded_edge_to_point.x, rounded_edge_to_point.y)) -
462      corner_radius;
463
464    let vertical_border = select(quad.border_widths.left, quad.border_widths.right, center_to_point.x > 0.0);
465    let horizontal_border = select(quad.border_widths.top, quad.border_widths.bottom, center_to_point.y > 0.0);
466    let inset_size = half_size - corner_radius - vec2<f32>(vertical_border, horizontal_border);
467    let point_to_inset_corner = abs(center_to_point) - inset_size;
468
469    var border_width = 0.0;
470    if (point_to_inset_corner.x < 0.0 && point_to_inset_corner.y < 0.0) {
471        border_width = 0.0;
472    } else if (point_to_inset_corner.y > point_to_inset_corner.x) {
473        border_width = horizontal_border;
474    } else {
475        border_width = vertical_border;
476    }
477
478    var color = background_color;
479    if (border_width > 0.0) {
480        let inset_distance = distance + border_width;
481        // Blend the border on top of the background and then linearly interpolate
482        // between the two as we slide inside the background.
483        let blended_border = over(background_color, input.border_color);
484        color = mix(blended_border, background_color,
485                    saturate(0.5 - inset_distance));
486    }
487
488    return blend_color(color, saturate(0.5 - distance));
489}
490
491// --- shadows --- //
492
493struct Shadow {
494    order: u32,
495    blur_radius: f32,
496    bounds: Bounds,
497    corner_radii: Corners,
498    content_mask: Bounds,
499    color: Hsla,
500}
501var<storage, read> b_shadows: array<Shadow>;
502
503struct ShadowVarying {
504    @builtin(position) position: vec4<f32>,
505    @location(0) @interpolate(flat) color: vec4<f32>,
506    @location(1) @interpolate(flat) shadow_id: u32,
507    //TODO: use `clip_distance` once Naga supports it
508    @location(3) clip_distances: vec4<f32>,
509}
510
511@vertex
512fn vs_shadow(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> ShadowVarying {
513    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
514    var shadow = b_shadows[instance_id];
515
516    let margin = 3.0 * shadow.blur_radius;
517    // Set the bounds of the shadow and adjust its size based on the shadow's
518    // spread radius to achieve the spreading effect
519    shadow.bounds.origin -= vec2<f32>(margin);
520    shadow.bounds.size += 2.0 * vec2<f32>(margin);
521
522    var out = ShadowVarying();
523    out.position = to_device_position(unit_vertex, shadow.bounds);
524    out.color = hsla_to_rgba(shadow.color);
525    out.shadow_id = instance_id;
526    out.clip_distances = distance_from_clip_rect(unit_vertex, shadow.bounds, shadow.content_mask);
527    return out;
528}
529
530@fragment
531fn fs_shadow(input: ShadowVarying) -> @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 shadow = b_shadows[input.shadow_id];
538    let half_size = shadow.bounds.size / 2.0;
539    let center = shadow.bounds.origin + half_size;
540    let center_to_point = input.position.xy - center;
541
542    let corner_radius = pick_corner_radius(center_to_point, shadow.corner_radii);
543
544    // The signal is only non-zero in a limited range, so don't waste samples
545    let low = center_to_point.y - half_size.y;
546    let high = center_to_point.y + half_size.y;
547    let start = clamp(-3.0 * shadow.blur_radius, low, high);
548    let end = clamp(3.0 * shadow.blur_radius, low, high);
549
550    // Accumulate samples (we can get away with surprisingly few samples)
551    let step = (end - start) / 4.0;
552    var y = start + step * 0.5;
553    var alpha = 0.0;
554    for (var i = 0; i < 4; i += 1) {
555        let blur = blur_along_x(center_to_point.x, center_to_point.y - y,
556            shadow.blur_radius, corner_radius, half_size);
557        alpha +=  blur * gaussian(y, shadow.blur_radius) * step;
558        y += step;
559    }
560
561    return blend_color(input.color, alpha);
562}
563
564// --- path rasterization --- //
565
566struct PathVertex {
567    xy_position: vec2<f32>,
568    st_position: vec2<f32>,
569    content_mask: Bounds,
570}
571var<storage, read> b_path_vertices: array<PathVertex>;
572
573struct PathRasterizationVarying {
574    @builtin(position) position: vec4<f32>,
575    @location(0) st_position: vec2<f32>,
576    //TODO: use `clip_distance` once Naga supports it
577    @location(3) clip_distances: vec4<f32>,
578}
579
580@vertex
581fn vs_path_rasterization(@builtin(vertex_index) vertex_id: u32) -> PathRasterizationVarying {
582    let v = b_path_vertices[vertex_id];
583
584    var out = PathRasterizationVarying();
585    out.position = to_device_position_impl(v.xy_position);
586    out.st_position = v.st_position;
587    out.clip_distances = distance_from_clip_rect_impl(v.xy_position, v.content_mask);
588    return out;
589}
590
591@fragment
592fn fs_path_rasterization(input: PathRasterizationVarying) -> @location(0) f32 {
593    let dx = dpdx(input.st_position);
594    let dy = dpdy(input.st_position);
595    if (any(input.clip_distances < vec4<f32>(0.0))) {
596        return 0.0;
597    }
598
599    let gradient = 2.0 * input.st_position.xx * vec2<f32>(dx.x, dy.x) - vec2<f32>(dx.y, dy.y);
600    let f = input.st_position.x * input.st_position.x - input.st_position.y;
601    let distance = f / length(gradient);
602    return saturate(0.5 - distance);
603}
604
605// --- paths --- //
606
607struct PathSprite {
608    bounds: Bounds,
609    color: Background,
610    tile: AtlasTile,
611}
612var<storage, read> b_path_sprites: array<PathSprite>;
613
614struct PathVarying {
615    @builtin(position) position: vec4<f32>,
616    @location(0) tile_position: vec2<f32>,
617    @location(1) @interpolate(flat) instance_id: u32,
618    @location(2) @interpolate(flat) color_solid: vec4<f32>,
619    @location(3) @interpolate(flat) color0: vec4<f32>,
620    @location(4) @interpolate(flat) color1: vec4<f32>,
621}
622
623@vertex
624fn vs_path(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PathVarying {
625    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
626    let sprite = b_path_sprites[instance_id];
627    // Don't apply content mask because it was already accounted for when rasterizing the path.
628
629    var out = PathVarying();
630    out.position = to_device_position(unit_vertex, sprite.bounds);
631    out.tile_position = to_tile_position(unit_vertex, sprite.tile);
632    out.instance_id = instance_id;
633
634    let gradient = prepare_gradient_color(
635        sprite.color.tag,
636        sprite.color.color_space,
637        sprite.color.solid,
638        sprite.color.colors
639    );
640    out.color_solid = gradient.solid;
641    out.color0 = gradient.color0;
642    out.color1 = gradient.color1;
643    return out;
644}
645
646@fragment
647fn fs_path(input: PathVarying) -> @location(0) vec4<f32> {
648    let sample = textureSample(t_sprite, s_sprite, input.tile_position).r;
649    let mask = 1.0 - abs(1.0 - sample % 2.0);
650    let sprite = b_path_sprites[input.instance_id];
651    let background = sprite.color;
652    let color = gradient_color(background, input.position.xy, sprite.bounds,
653        input.color_solid, input.color0, input.color1);
654    return blend_color(color, mask);
655}
656
657// --- underlines --- //
658
659struct Underline {
660    order: u32,
661    pad: u32,
662    bounds: Bounds,
663    content_mask: Bounds,
664    color: Hsla,
665    thickness: f32,
666    wavy: u32,
667}
668var<storage, read> b_underlines: array<Underline>;
669
670struct UnderlineVarying {
671    @builtin(position) position: vec4<f32>,
672    @location(0) @interpolate(flat) color: vec4<f32>,
673    @location(1) @interpolate(flat) underline_id: u32,
674    //TODO: use `clip_distance` once Naga supports it
675    @location(3) clip_distances: vec4<f32>,
676}
677
678@vertex
679fn vs_underline(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> UnderlineVarying {
680    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
681    let underline = b_underlines[instance_id];
682
683    var out = UnderlineVarying();
684    out.position = to_device_position(unit_vertex, underline.bounds);
685    out.color = hsla_to_rgba(underline.color);
686    out.underline_id = instance_id;
687    out.clip_distances = distance_from_clip_rect(unit_vertex, underline.bounds, underline.content_mask);
688    return out;
689}
690
691@fragment
692fn fs_underline(input: UnderlineVarying) -> @location(0) vec4<f32> {
693    // Alpha clip first, since we don't have `clip_distance`.
694    if (any(input.clip_distances < vec4<f32>(0.0))) {
695        return vec4<f32>(0.0);
696    }
697
698    let underline = b_underlines[input.underline_id];
699    if ((underline.wavy & 0xFFu) == 0u)
700    {
701        return blend_color(input.color, input.color.a);
702    }
703
704    let half_thickness = underline.thickness * 0.5;
705    let st = (input.position.xy - underline.bounds.origin) / underline.bounds.size.y - vec2<f32>(0.0, 0.5);
706    let frequency = M_PI_F * 3.0 * underline.thickness / 3.0;
707    let amplitude = 1.0 / (4.0 * underline.thickness);
708    let sine = sin(st.x * frequency) * amplitude;
709    let dSine = cos(st.x * frequency) * amplitude * frequency;
710    let distance = (st.y - sine) / sqrt(1.0 + dSine * dSine);
711    let distance_in_pixels = distance * underline.bounds.size.y;
712    let distance_from_top_border = distance_in_pixels - half_thickness;
713    let distance_from_bottom_border = distance_in_pixels + half_thickness;
714    let alpha = saturate(0.5 - max(-distance_from_bottom_border, distance_from_top_border));
715    return blend_color(input.color, alpha * input.color.a);
716}
717
718// --- monochrome sprites --- //
719
720struct MonochromeSprite {
721    order: u32,
722    pad: u32,
723    bounds: Bounds,
724    content_mask: Bounds,
725    color: Hsla,
726    tile: AtlasTile,
727    transformation: TransformationMatrix,
728}
729var<storage, read> b_mono_sprites: array<MonochromeSprite>;
730
731struct MonoSpriteVarying {
732    @builtin(position) position: vec4<f32>,
733    @location(0) tile_position: vec2<f32>,
734    @location(1) @interpolate(flat) color: vec4<f32>,
735    @location(3) clip_distances: vec4<f32>,
736}
737
738@vertex
739fn vs_mono_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> MonoSpriteVarying {
740    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
741    let sprite = b_mono_sprites[instance_id];
742
743    var out = MonoSpriteVarying();
744    out.position = to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation);
745
746    out.tile_position = to_tile_position(unit_vertex, sprite.tile);
747    out.color = hsla_to_rgba(sprite.color);
748    out.clip_distances = distance_from_clip_rect(unit_vertex, sprite.bounds, sprite.content_mask);
749    return out;
750}
751
752@fragment
753fn fs_mono_sprite(input: MonoSpriteVarying) -> @location(0) vec4<f32> {
754    let sample = textureSample(t_sprite, s_sprite, input.tile_position).r;
755    // Alpha clip after using the derivatives.
756    if (any(input.clip_distances < vec4<f32>(0.0))) {
757        return vec4<f32>(0.0);
758    }
759    return blend_color(input.color, sample);
760}
761
762// --- polychrome sprites --- //
763
764struct PolychromeSprite {
765    order: u32,
766    pad: u32,
767    grayscale: u32,
768    opacity: f32,
769    bounds: Bounds,
770    content_mask: Bounds,
771    corner_radii: Corners,
772    tile: AtlasTile,
773}
774var<storage, read> b_poly_sprites: array<PolychromeSprite>;
775
776struct PolySpriteVarying {
777    @builtin(position) position: vec4<f32>,
778    @location(0) tile_position: vec2<f32>,
779    @location(1) @interpolate(flat) sprite_id: u32,
780    @location(3) clip_distances: vec4<f32>,
781}
782
783@vertex
784fn vs_poly_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PolySpriteVarying {
785    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
786    let sprite = b_poly_sprites[instance_id];
787
788    var out = PolySpriteVarying();
789    out.position = to_device_position(unit_vertex, sprite.bounds);
790    out.tile_position = to_tile_position(unit_vertex, sprite.tile);
791    out.sprite_id = instance_id;
792    out.clip_distances = distance_from_clip_rect(unit_vertex, sprite.bounds, sprite.content_mask);
793    return out;
794}
795
796@fragment
797fn fs_poly_sprite(input: PolySpriteVarying) -> @location(0) vec4<f32> {
798    let sample = textureSample(t_sprite, s_sprite, input.tile_position);
799    // Alpha clip after using the derivatives.
800    if (any(input.clip_distances < vec4<f32>(0.0))) {
801        return vec4<f32>(0.0);
802    }
803
804    let sprite = b_poly_sprites[input.sprite_id];
805    let distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii);
806
807    var color = sample;
808    if ((sprite.grayscale & 0xFFu) != 0u) {
809        let grayscale = dot(color.rgb, GRAYSCALE_FACTORS);
810        color = vec4<f32>(vec3<f32>(grayscale), sample.a);
811    }
812    return blend_color(color, sprite.opacity * saturate(0.5 - distance));
813}
814
815// --- surfaces --- //
816
817struct SurfaceParams {
818    bounds: Bounds,
819    content_mask: Bounds,
820}
821
822var<uniform> surface_locals: SurfaceParams;
823var t_y: texture_2d<f32>;
824var t_cb_cr: texture_2d<f32>;
825var s_surface: sampler;
826
827const ycbcr_to_RGB = mat4x4<f32>(
828    vec4<f32>( 1.0000f,  1.0000f,  1.0000f, 0.0),
829    vec4<f32>( 0.0000f, -0.3441f,  1.7720f, 0.0),
830    vec4<f32>( 1.4020f, -0.7141f,  0.0000f, 0.0),
831    vec4<f32>(-0.7010f,  0.5291f, -0.8860f, 1.0),
832);
833
834struct SurfaceVarying {
835    @builtin(position) position: vec4<f32>,
836    @location(0) texture_position: vec2<f32>,
837    @location(3) clip_distances: vec4<f32>,
838}
839
840@vertex
841fn vs_surface(@builtin(vertex_index) vertex_id: u32) -> SurfaceVarying {
842    let unit_vertex = vec2<f32>(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u));
843
844    var out = SurfaceVarying();
845    out.position = to_device_position(unit_vertex, surface_locals.bounds);
846    out.texture_position = unit_vertex;
847    out.clip_distances = distance_from_clip_rect(unit_vertex, surface_locals.bounds, surface_locals.content_mask);
848    return out;
849}
850
851@fragment
852fn fs_surface(input: SurfaceVarying) -> @location(0) vec4<f32> {
853    // Alpha clip after using the derivatives.
854    if (any(input.clip_distances < vec4<f32>(0.0))) {
855        return vec4<f32>(0.0);
856    }
857
858    let y_cb_cr = vec4<f32>(
859        textureSampleLevel(t_y, s_surface, input.texture_position, 0.0).r,
860        textureSampleLevel(t_cb_cr, s_surface, input.texture_position, 0.0).rg,
861        1.0);
862
863    return ycbcr_to_RGB * y_cb_cr;
864}