shaders.hlsl

   1cbuffer GlobalParams: register(b0) {
   2    float2 global_viewport_size;
   3    uint2 _pad;
   4};
   5
   6Texture2D<float4> t_sprite: register(t0);
   7SamplerState s_sprite: register(s0);
   8
   9struct Bounds {
  10    float2 origin;
  11    float2 size;
  12};
  13
  14struct Corners {
  15    float top_left;
  16    float top_right;
  17    float bottom_right;
  18    float bottom_left;
  19};
  20
  21struct Edges {
  22    float top;
  23    float right;
  24    float bottom;
  25    float left;
  26};
  27
  28struct Hsla {
  29    float h;
  30    float s;
  31    float l;
  32    float a;
  33};
  34
  35struct LinearColorStop {
  36    Hsla color;
  37    float percentage;
  38};
  39
  40struct Background {
  41    // 0u is Solid
  42    // 1u is LinearGradient
  43    // 2u is PatternSlash
  44    uint tag;
  45    // 0u is sRGB linear color
  46    // 1u is Oklab color
  47    uint color_space;
  48    Hsla solid;
  49    float gradient_angle_or_pattern_height;
  50    LinearColorStop colors[2];
  51    uint pad;
  52};
  53
  54struct GradientColor {
  55  float4 solid;
  56  float4 color0;
  57  float4 color1;
  58};
  59
  60struct AtlasTextureId {
  61    uint index;
  62    uint kind;
  63};
  64
  65struct AtlasBounds {
  66    int2 origin;
  67    int2 size;
  68};
  69
  70struct AtlasTile {
  71    AtlasTextureId texture_id;
  72    uint tile_id;
  73    uint padding;
  74    AtlasBounds bounds;
  75};
  76
  77struct TransformationMatrix {
  78    float2x2 rotation_scale;
  79    float2 translation;
  80};
  81
  82static const float M_PI_F = 3.141592653f;
  83static const float3 GRAYSCALE_FACTORS = float3(0.2126f, 0.7152f, 0.0722f);
  84
  85float4 to_device_position_impl(float2 position) {
  86    float2 device_position = position / global_viewport_size * float2(2.0, -2.0) + float2(-1.0, 1.0);
  87    return float4(device_position, 0., 1.);
  88}
  89
  90float4 to_device_position(float2 unit_vertex, Bounds bounds) {
  91    float2 position = unit_vertex * bounds.size + bounds.origin;
  92    return to_device_position_impl(position);
  93}
  94
  95float4 distance_from_clip_rect_impl(float2 position, Bounds clip_bounds) {
  96    float2 tl = position - clip_bounds.origin;
  97    float2 br = clip_bounds.origin + clip_bounds.size - position;
  98    return float4(tl.x, br.x, tl.y, br.y);
  99}
 100
 101float4 distance_from_clip_rect(float2 unit_vertex, Bounds bounds, Bounds clip_bounds) {
 102    float2 position = unit_vertex * bounds.size + bounds.origin;
 103    return distance_from_clip_rect_impl(position, clip_bounds);
 104}
 105
 106// Convert linear RGB to sRGB
 107float3 linear_to_srgb(float3 color) {
 108    return pow(color, float3(2.2, 2.2, 2.2));
 109}
 110
 111// Convert sRGB to linear RGB
 112float3 srgb_to_linear(float3 color) {
 113    return pow(color, float3(1.0 / 2.2, 1.0 / 2.2, 1.0 / 2.2));
 114}
 115
 116/// Hsla to linear RGBA conversion.
 117float4 hsla_to_rgba(Hsla hsla) {
 118    float h = hsla.h * 6.0; // Now, it's an angle but scaled in [0, 6) range
 119    float s = hsla.s;
 120    float l = hsla.l;
 121    float a = hsla.a;
 122
 123    float c = (1.0 - abs(2.0 * l - 1.0)) * s;
 124    float x = c * (1.0 - abs(fmod(h, 2.0) - 1.0));
 125    float m = l - c / 2.0;
 126
 127    float r = 0.0;
 128    float g = 0.0;
 129    float b = 0.0;
 130
 131    if (h >= 0.0 && h < 1.0) {
 132        r = c;
 133        g = x;
 134        b = 0.0;
 135    } else if (h >= 1.0 && h < 2.0) {
 136        r = x;
 137        g = c;
 138        b = 0.0;
 139    } else if (h >= 2.0 && h < 3.0) {
 140        r = 0.0;
 141        g = c;
 142        b = x;
 143    } else if (h >= 3.0 && h < 4.0) {
 144        r = 0.0;
 145        g = x;
 146        b = c;
 147    } else if (h >= 4.0 && h < 5.0) {
 148        r = x;
 149        g = 0.0;
 150        b = c;
 151    } else {
 152        r = c;
 153        g = 0.0;
 154        b = x;
 155    }
 156
 157    float4 rgba;
 158    rgba.x = (r + m);
 159    rgba.y = (g + m);
 160    rgba.z = (b + m);
 161    rgba.w = a;
 162    return rgba;
 163}
 164
 165// Converts a sRGB color to the Oklab color space.
 166// Reference: https://bottosson.github.io/posts/oklab/#converting-from-linear-srgb-to-oklab
 167float4 srgb_to_oklab(float4 color) {
 168    // Convert non-linear sRGB to linear sRGB
 169    color = float4(srgb_to_linear(color.rgb), color.a);
 170
 171    float l = 0.4122214708 * color.r + 0.5363325363 * color.g + 0.0514459929 * color.b;
 172    float m = 0.2119034982 * color.r + 0.6806995451 * color.g + 0.1073969566 * color.b;
 173    float s = 0.0883024619 * color.r + 0.2817188376 * color.g + 0.6299787005 * color.b;
 174
 175    float l_ = pow(l, 1.0/3.0);
 176    float m_ = pow(m, 1.0/3.0);
 177    float s_ = pow(s, 1.0/3.0);
 178
 179    return float4(
 180        0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,
 181        1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,
 182        0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,
 183        color.a
 184    );
 185}
 186
 187// Converts an Oklab color to the sRGB color space.
 188float4 oklab_to_srgb(float4 color) {
 189    float l_ = color.r + 0.3963377774 * color.g + 0.2158037573 * color.b;
 190    float m_ = color.r - 0.1055613458 * color.g - 0.0638541728 * color.b;
 191    float s_ = color.r - 0.0894841775 * color.g - 1.2914855480 * color.b;
 192
 193    float l = l_ * l_ * l_;
 194    float m = m_ * m_ * m_;
 195    float s = s_ * s_ * s_;
 196
 197    float3 linear_rgb = float3(
 198        4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
 199        -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
 200        -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s
 201    );
 202
 203    // Convert linear sRGB to non-linear sRGB
 204    return float4(linear_to_srgb(linear_rgb), color.a);
 205}
 206
 207// This approximates the error function, needed for the gaussian integral
 208float2 erf(float2 x) {
 209    float2 s = sign(x);
 210    float2 a = abs(x);
 211    x = 1. + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;
 212    x *= x;
 213    return s - s / (x * x);
 214}
 215
 216float blur_along_x(float x, float y, float sigma, float corner, float2 half_size) {
 217    float delta = min(half_size.y - corner - abs(y), 0.);
 218    float curved = half_size.x - corner + sqrt(max(0., corner * corner - delta * delta));
 219    float2 integral = 0.5 + 0.5 * erf((x + float2(-curved, curved)) * (sqrt(0.5) / sigma));
 220    return integral.y - integral.x;
 221}
 222
 223// A standard gaussian function, used for weighting samples
 224float gaussian(float x, float sigma) {
 225    return exp(-(x * x) / (2. * sigma * sigma)) / (sqrt(2. * M_PI_F) * sigma);
 226}
 227
 228float4 over(float4 below, float4 above) {
 229    float4 result;
 230    float alpha = above.a + below.a * (1.0 - above.a);
 231    result.rgb = (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha;
 232    result.a = alpha;
 233    return result;
 234}
 235
 236float2 to_tile_position(float2 unit_vertex, AtlasTile tile) {
 237    float2 atlas_size;
 238    t_sprite.GetDimensions(atlas_size.x, atlas_size.y);
 239    return (float2(tile.bounds.origin) + unit_vertex * float2(tile.bounds.size)) / atlas_size;
 240}
 241
 242// Selects corner radius based on quadrant.
 243float pick_corner_radius(float2 center_to_point, Corners corner_radii) {
 244    if (center_to_point.x < 0.) {
 245        if (center_to_point.y < 0.) {
 246            return corner_radii.top_left;
 247        } else {
 248            return corner_radii.bottom_left;
 249        }
 250    } else {
 251        if (center_to_point.y < 0.) {
 252            return corner_radii.top_right;
 253        } else {
 254            return corner_radii.bottom_right;
 255        }
 256    }
 257}
 258
 259float4 to_device_position_transformed(float2 unit_vertex, Bounds bounds,
 260                                      TransformationMatrix transformation) {
 261    float2 position = unit_vertex * bounds.size + bounds.origin;
 262    float2 transformed = mul(position, transformation.rotation_scale) + transformation.translation;
 263    float2 device_position = transformed / global_viewport_size * float2(2.0, -2.0) + float2(-1.0, 1.0);
 264    return float4(device_position, 0.0, 1.0);
 265}
 266
 267// Implementation of quad signed distance field
 268float quad_sdf_impl(float2 corner_center_to_point, float corner_radius) {
 269    if (corner_radius == 0.0) {
 270        // Fast path for unrounded corners
 271        return max(corner_center_to_point.x, corner_center_to_point.y);
 272    } else {
 273        // Signed distance of the point from a quad that is inset by corner_radius
 274        // It is negative inside this quad, and positive outside
 275        float signed_distance_to_inset_quad =
 276            // 0 inside the inset quad, and positive outside
 277            length(max(float2(0.0, 0.0), corner_center_to_point)) +
 278            // 0 outside the inset quad, and negative inside
 279            min(0.0, max(corner_center_to_point.x, corner_center_to_point.y));
 280
 281        return signed_distance_to_inset_quad - corner_radius;
 282    }
 283}
 284
 285float quad_sdf(float2 pt, Bounds bounds, Corners corner_radii) {
 286    float2 half_size = bounds.size / 2.;
 287    float2 center = bounds.origin + half_size;
 288    float2 center_to_point = pt - center;
 289    float corner_radius = pick_corner_radius(center_to_point, corner_radii);
 290    float2 corner_to_point = abs(center_to_point) - half_size;
 291    float2 corner_center_to_point = corner_to_point + corner_radius;
 292    return quad_sdf_impl(corner_center_to_point, corner_radius);
 293}
 294
 295GradientColor prepare_gradient_color(uint tag, uint color_space, Hsla solid, LinearColorStop colors[2]) {
 296    GradientColor output;
 297    if (tag == 0 || tag == 2) {
 298        output.solid = hsla_to_rgba(solid);
 299    } else if (tag == 1) {
 300        output.color0 = hsla_to_rgba(colors[0].color);
 301        output.color1 = hsla_to_rgba(colors[1].color);
 302
 303        // Prepare color space in vertex for avoid conversion
 304        // in fragment shader for performance reasons
 305        if (color_space == 1) {
 306            // Oklab
 307            output.color0 = srgb_to_oklab(output.color0);
 308            output.color1 = srgb_to_oklab(output.color1);
 309        }
 310    }
 311
 312    return output;
 313}
 314
 315float2x2 rotate2d(float angle) {
 316    float s = sin(angle);
 317    float c = cos(angle);
 318    return float2x2(c, -s, s, c);
 319}
 320
 321float4 gradient_color(Background background,
 322                      float2 position,
 323                      Bounds bounds,
 324                      float4 solid_color, float4 color0, float4 color1) {
 325    float4 color;
 326
 327    switch (background.tag) {
 328        case 0:
 329            color = solid_color;
 330            break;
 331        case 1: {
 332            // -90 degrees to match the CSS gradient angle.
 333            float gradient_angle = background.gradient_angle_or_pattern_height;
 334            float radians = (fmod(gradient_angle, 360.0) - 90.0) * (M_PI_F / 180.0);
 335            float2 direction = float2(cos(radians), sin(radians));
 336
 337            // Expand the short side to be the same as the long side
 338            if (bounds.size.x > bounds.size.y) {
 339                direction.y *= bounds.size.y / bounds.size.x;
 340            } else {
 341                direction.x *=  bounds.size.x / bounds.size.y;
 342            }
 343
 344            // Get the t value for the linear gradient with the color stop percentages.
 345            float2 half_size = bounds.size * 0.5;
 346            float2 center = bounds.origin + half_size;
 347            float2 center_to_point = position - center;
 348            float t = dot(center_to_point, direction) / length(direction);
 349            // Check the direct to determine the use x or y
 350            if (abs(direction.x) > abs(direction.y)) {
 351                t = (t + half_size.x) / bounds.size.x;
 352            } else {
 353                t = (t + half_size.y) / bounds.size.y;
 354            }
 355
 356            // Adjust t based on the stop percentages
 357            t = (t - background.colors[0].percentage)
 358                / (background.colors[1].percentage
 359                - background.colors[0].percentage);
 360            t = clamp(t, 0.0, 1.0);
 361
 362            switch (background.color_space) {
 363                case 0:
 364                    color = lerp(color0, color1, t);
 365                    break;
 366                case 1: {
 367                    float4 oklab_color = lerp(color0, color1, t);
 368                    color = oklab_to_srgb(oklab_color);
 369                    break;
 370                }
 371            }
 372            break;
 373        }
 374        case 2: {
 375            float gradient_angle_or_pattern_height = background.gradient_angle_or_pattern_height;
 376            float pattern_width = (gradient_angle_or_pattern_height / 65535.0f) / 255.0f;
 377            float pattern_interval = fmod(gradient_angle_or_pattern_height, 65535.0f) / 255.0f;
 378            float pattern_height = pattern_width + pattern_interval;
 379            float stripe_angle = M_PI_F / 4.0;
 380            float pattern_period = pattern_height * sin(stripe_angle);
 381            float2x2 rotation = rotate2d(stripe_angle);
 382            float2 relative_position = position - bounds.origin;
 383            float2 rotated_point = mul(rotation, relative_position);
 384            float pattern = fmod(rotated_point.x, pattern_period);
 385            float distance = min(pattern, pattern_period - pattern) - pattern_period * (pattern_width / pattern_height) /  2.0f;
 386            color = solid_color;
 387            color.a *= saturate(0.5 - distance);
 388            break;
 389        }
 390    }
 391
 392    return color;
 393}
 394
 395// Returns the dash velocity of a corner given the dash velocity of the two
 396// sides, by returning the slower velocity (larger dashes).
 397//
 398// Since 0 is used for dash velocity when the border width is 0 (instead of
 399// +inf), this returns the other dash velocity in that case.
 400//
 401// An alternative to this might be to appropriately interpolate the dash
 402// velocity around the corner, but that seems overcomplicated.
 403float corner_dash_velocity(float dv1, float dv2) {
 404    if (dv1 == 0.0) {
 405        return dv2;
 406    } else if (dv2 == 0.0) {
 407        return dv1;
 408    } else {
 409        return min(dv1, dv2);
 410    }
 411}
 412
 413// Returns alpha used to render antialiased dashes.
 414// `t` is within the dash when `fmod(t, period) < length`.
 415float dash_alpha(
 416    float t, float period, float length, float dash_velocity,
 417    float antialias_threshold
 418) {
 419    float half_period = period / 2.0;
 420    float half_length = length / 2.0;
 421    // Value in [-half_period, half_period]
 422    // The dash is in [-half_length, half_length]
 423    float centered = fmod(t + half_period - half_length, period) - half_period;
 424    // Signed distance for the dash, negative values are inside the dash
 425    float signed_distance = abs(centered) - half_length;
 426    // Antialiased alpha based on the signed distance
 427    return saturate(antialias_threshold - signed_distance / dash_velocity);
 428}
 429
 430// This approximates distance to the nearest point to a quarter ellipse in a way
 431// that is sufficient for anti-aliasing when the ellipse is not very eccentric.
 432// The components of `point` are expected to be positive.
 433//
 434// Negative on the outside and positive on the inside.
 435float quarter_ellipse_sdf(float2 pt, float2 radii) {
 436    // Scale the space to treat the ellipse like a unit circle
 437    float2 circle_vec = pt / radii;
 438    float unit_circle_sdf = length(circle_vec) - 1.0;
 439    // Approximate up-scaling of the length by using the average of the radii.
 440    //
 441    // TODO: A better solution would be to use the gradient of the implicit
 442    // function for an ellipse to approximate a scaling factor.
 443    return unit_circle_sdf * (radii.x + radii.y) * -0.5;
 444}
 445
 446/*
 447**
 448**              Quads
 449**
 450*/
 451
 452struct Quad {
 453    uint order;
 454    uint border_style;
 455    Bounds bounds;
 456    Bounds content_mask;
 457    Background background;
 458    Hsla border_color;
 459    Corners corner_radii;
 460    Edges border_widths;
 461};
 462
 463struct QuadVertexOutput {
 464    nointerpolation uint quad_id: TEXCOORD0;
 465    float4 position: SV_Position;
 466    nointerpolation float4 border_color: COLOR0;
 467    nointerpolation float4 background_solid: COLOR1;
 468    nointerpolation float4 background_color0: COLOR2;
 469    nointerpolation float4 background_color1: COLOR3;
 470    float4 clip_distance: SV_ClipDistance;
 471};
 472
 473struct QuadFragmentInput {
 474    nointerpolation uint quad_id: TEXCOORD0;
 475    float4 position: SV_Position;
 476    nointerpolation float4 border_color: COLOR0;
 477    nointerpolation float4 background_solid: COLOR1;
 478    nointerpolation float4 background_color0: COLOR2;
 479    nointerpolation float4 background_color1: COLOR3;
 480};
 481
 482StructuredBuffer<Quad> quads: register(t1);
 483
 484QuadVertexOutput quad_vertex(uint vertex_id: SV_VertexID, uint quad_id: SV_InstanceID) {
 485    float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
 486    Quad quad = quads[quad_id];
 487    float4 device_position = to_device_position(unit_vertex, quad.bounds);
 488
 489    GradientColor gradient = prepare_gradient_color(
 490        quad.background.tag,
 491        quad.background.color_space,
 492        quad.background.solid,
 493        quad.background.colors
 494    );
 495    float4 clip_distance = distance_from_clip_rect(unit_vertex, quad.bounds, quad.content_mask);
 496    float4 border_color = hsla_to_rgba(quad.border_color);
 497
 498    QuadVertexOutput output;
 499    output.position = device_position;
 500    output.border_color = border_color;
 501    output.quad_id = quad_id;
 502    output.background_solid = gradient.solid;
 503    output.background_color0 = gradient.color0;
 504    output.background_color1 = gradient.color1;
 505    output.clip_distance = clip_distance;
 506    return output;
 507}
 508
 509float4 quad_fragment(QuadFragmentInput input): SV_Target {
 510    Quad quad = quads[input.quad_id];
 511    float4 background_color = gradient_color(quad.background, input.position.xy, quad.bounds,
 512    input.background_solid, input.background_color0, input.background_color1);
 513
 514    bool unrounded = quad.corner_radii.top_left == 0.0 &&
 515        quad.corner_radii.top_right == 0.0 &&
 516        quad.corner_radii.bottom_left == 0.0 &&
 517        quad.corner_radii.bottom_right == 0.0;
 518
 519    // Fast path when the quad is not rounded and doesn't have any border
 520    if (quad.border_widths.top == 0.0 &&
 521        quad.border_widths.left == 0.0 &&
 522        quad.border_widths.right == 0.0 &&
 523        quad.border_widths.bottom == 0.0 &&
 524        unrounded) {
 525        return background_color;
 526    }
 527
 528    float2 size = quad.bounds.size;
 529    float2 half_size = size / 2.;
 530    float2 the_point = input.position.xy - quad.bounds.origin;
 531    float2 center_to_point = the_point - half_size;
 532
 533    // Signed distance field threshold for inclusion of pixels. 0.5 is the
 534    // minimum distance between the center of the pixel and the edge.
 535    const float antialias_threshold = 0.5;
 536
 537    // Radius of the nearest corner
 538    float corner_radius = pick_corner_radius(center_to_point, quad.corner_radii);
 539
 540    float2 border = float2(
 541        center_to_point.x < 0.0 ? quad.border_widths.left : quad.border_widths.right,
 542        center_to_point.y < 0.0 ? quad.border_widths.top : quad.border_widths.bottom
 543    );
 544
 545    // 0-width borders are reduced so that `inner_sdf >= antialias_threshold`.
 546    // The purpose of this is to not draw antialiasing pixels in this case.
 547    float2 reduced_border = float2(
 548        border.x == 0.0 ? -antialias_threshold : border.x,
 549        border.y == 0.0 ? -antialias_threshold : border.y
 550    );
 551
 552    // Vector from the corner of the quad bounds to the point, after mirroring
 553    // the point into the bottom right quadrant. Both components are <= 0.
 554    float2 corner_to_point = abs(center_to_point) - half_size;
 555
 556    // Vector from the point to the center of the rounded corner's circle, also
 557    // mirrored into bottom right quadrant.
 558    float2 corner_center_to_point = corner_to_point + corner_radius;
 559
 560    // Whether the nearest point on the border is rounded
 561    bool is_near_rounded_corner =
 562        corner_center_to_point.x >= 0.0 &&
 563        corner_center_to_point.y >= 0.0;
 564
 565    // Vector from straight border inner corner to point.
 566    //
 567    // 0-width borders are turned into width -1 so that inner_sdf is > 1.0 near
 568    // the border. Without this, antialiasing pixels would be drawn.
 569    float2 straight_border_inner_corner_to_point = corner_to_point + reduced_border;
 570
 571    // Whether the point is beyond the inner edge of the straight border
 572    bool is_beyond_inner_straight_border =
 573        straight_border_inner_corner_to_point.x > 0.0 ||
 574        straight_border_inner_corner_to_point.y > 0.0;
 575
 576    // Whether the point is far enough inside the quad, such that the pixels are
 577    // not affected by the straight border.
 578    bool is_within_inner_straight_border =
 579        straight_border_inner_corner_to_point.x < -antialias_threshold &&
 580        straight_border_inner_corner_to_point.y < -antialias_threshold;
 581
 582    // Fast path for points that must be part of the background
 583    if (is_within_inner_straight_border && !is_near_rounded_corner) {
 584        return background_color;
 585    }
 586
 587    // Signed distance of the point to the outside edge of the quad's border
 588    float outer_sdf = quad_sdf_impl(corner_center_to_point, corner_radius);
 589
 590    // Approximate signed distance of the point to the inside edge of the quad's
 591    // border. It is negative outside this edge (within the border), and
 592    // positive inside.
 593    //
 594    // This is not always an accurate signed distance:
 595    // * The rounded portions with varying border width use an approximation of
 596    //   nearest-point-on-ellipse.
 597    // * When it is quickly known to be outside the edge, -1.0 is used.
 598    float inner_sdf = 0.0;
 599    if (corner_center_to_point.x <= 0.0 || corner_center_to_point.y <= 0.0) {
 600        // Fast paths for straight borders
 601        inner_sdf = -max(straight_border_inner_corner_to_point.x,
 602                        straight_border_inner_corner_to_point.y);
 603    } else if (is_beyond_inner_straight_border) {
 604        // Fast path for points that must be outside the inner edge
 605        inner_sdf = -1.0;
 606    } else if (reduced_border.x == reduced_border.y) {
 607        // Fast path for circular inner edge.
 608        inner_sdf = -(outer_sdf + reduced_border.x);
 609    } else {
 610        float2 ellipse_radii = max(float2(0.0, 0.0), float2(corner_radius, corner_radius) - reduced_border);
 611        inner_sdf = quarter_ellipse_sdf(corner_center_to_point, ellipse_radii);
 612    }
 613
 614    // Negative when inside the border
 615    float border_sdf = max(inner_sdf, outer_sdf);
 616
 617    float4 color = background_color;
 618    if (border_sdf < antialias_threshold) {
 619        float4 border_color = input.border_color;
 620        // Dashed border logic when border_style == 1
 621        if (quad.border_style == 1) {
 622            // Position along the perimeter in "dash space", where each dash
 623            // period has length 1
 624            float t = 0.0;
 625
 626            // Total number of dash periods, so that the dash spacing can be
 627            // adjusted to evenly divide it
 628            float max_t = 0.0;
 629
 630            // Border width is proportional to dash size. This is the behavior
 631            // used by browsers, but also avoids dashes from different segments
 632            // overlapping when dash size is smaller than the border width.
 633            //
 634            // Dash pattern: (2 * border width) dash, (1 * border width) gap
 635            const float dash_length_per_width = 2.0;
 636            const float dash_gap_per_width = 1.0;
 637            const float dash_period_per_width = dash_length_per_width + dash_gap_per_width;
 638
 639            // Since the dash size is determined by border width, the density of
 640            // dashes varies. Multiplying a pixel distance by this returns a
 641            // position in dash space - it has units (dash period / pixels). So
 642            // a dash velocity of (1 / 10) is 1 dash every 10 pixels.
 643            float dash_velocity = 0.0;
 644
 645            // Dividing this by the border width gives the dash velocity
 646            const float dv_numerator = 1.0 / dash_period_per_width;
 647
 648            if (unrounded) {
 649                // When corners aren't rounded, the dashes are separately laid
 650                // out on each straight line, rather than around the whole
 651                // perimeter. This way each line starts and ends with a dash.
 652                bool is_horizontal = corner_center_to_point.x < corner_center_to_point.y;
 653                float border_width = is_horizontal ? border.x : border.y;
 654                dash_velocity = dv_numerator / border_width;
 655                t = is_horizontal ? the_point.x : the_point.y;
 656                t *= dash_velocity;
 657                max_t = is_horizontal ? size.x : size.y;
 658                max_t *= dash_velocity;
 659            } else {
 660                // When corners are rounded, the dashes are laid out clockwise
 661                // around the whole perimeter.
 662
 663                float r_tr = quad.corner_radii.top_right;
 664                float r_br = quad.corner_radii.bottom_right;
 665                float r_bl = quad.corner_radii.bottom_left;
 666                float r_tl = quad.corner_radii.top_left;
 667
 668                float w_t = quad.border_widths.top;
 669                float w_r = quad.border_widths.right;
 670                float w_b = quad.border_widths.bottom;
 671                float w_l = quad.border_widths.left;
 672
 673                // Straight side dash velocities
 674                float dv_t = w_t <= 0.0 ? 0.0 : dv_numerator / w_t;
 675                float dv_r = w_r <= 0.0 ? 0.0 : dv_numerator / w_r;
 676                float dv_b = w_b <= 0.0 ? 0.0 : dv_numerator / w_b;
 677                float dv_l = w_l <= 0.0 ? 0.0 : dv_numerator / w_l;
 678
 679                // Straight side lengths in dash space
 680                float s_t = (size.x - r_tl - r_tr) * dv_t;
 681                float s_r = (size.y - r_tr - r_br) * dv_r;
 682                float s_b = (size.x - r_br - r_bl) * dv_b;
 683                float s_l = (size.y - r_bl - r_tl) * dv_l;
 684
 685                float corner_dash_velocity_tr = corner_dash_velocity(dv_t, dv_r);
 686                float corner_dash_velocity_br = corner_dash_velocity(dv_b, dv_r);
 687                float corner_dash_velocity_bl = corner_dash_velocity(dv_b, dv_l);
 688                float corner_dash_velocity_tl = corner_dash_velocity(dv_t, dv_l);
 689
 690                // Corner lengths in dash space
 691                float c_tr = r_tr * (M_PI_F / 2.0) * corner_dash_velocity_tr;
 692                float c_br = r_br * (M_PI_F / 2.0) * corner_dash_velocity_br;
 693                float c_bl = r_bl * (M_PI_F / 2.0) * corner_dash_velocity_bl;
 694                float c_tl = r_tl * (M_PI_F / 2.0) * corner_dash_velocity_tl;
 695
 696                // Cumulative dash space upto each segment
 697                float upto_tr = s_t;
 698                float upto_r = upto_tr + c_tr;
 699                float upto_br = upto_r + s_r;
 700                float upto_b = upto_br + c_br;
 701                float upto_bl = upto_b + s_b;
 702                float upto_l = upto_bl + c_bl;
 703                float upto_tl = upto_l + s_l;
 704                max_t = upto_tl + c_tl;
 705
 706                if (is_near_rounded_corner) {
 707                    float radians = atan2(corner_center_to_point.y, corner_center_to_point.x);
 708                    float corner_t = radians * corner_radius;
 709
 710                    if (center_to_point.x >= 0.0) {
 711                        if (center_to_point.y < 0.0) {
 712                            dash_velocity = corner_dash_velocity_tr;
 713                            // Subtracted because radians is pi/2 to 0 when
 714                            // going clockwise around the top right corner,
 715                            // since the y axis has been flipped
 716                            t = upto_r - corner_t * dash_velocity;
 717                        } else {
 718                            dash_velocity = corner_dash_velocity_br;
 719                            // Added because radians is 0 to pi/2 when going
 720                            // clockwise around the bottom-right corner
 721                            t = upto_br + corner_t * dash_velocity;
 722                        }
 723                    } else {
 724                        if (center_to_point.y >= 0.0) {
 725                            dash_velocity = corner_dash_velocity_bl;
 726                            // Subtracted because radians is pi/1 to 0 when
 727                            // going clockwise around the bottom-left corner,
 728                            // since the x axis has been flipped
 729                            t = upto_l - corner_t * dash_velocity;
 730                        } else {
 731                            dash_velocity = corner_dash_velocity_tl;
 732                            // Added because radians is 0 to pi/2 when going
 733                            // clockwise around the top-left corner, since both
 734                            // axis were flipped
 735                            t = upto_tl + corner_t * dash_velocity;
 736                        }
 737                    }
 738                } else {
 739                    // Straight borders
 740                    bool is_horizontal = corner_center_to_point.x < corner_center_to_point.y;
 741                    if (is_horizontal) {
 742                        if (center_to_point.y < 0.0) {
 743                            dash_velocity = dv_t;
 744                            t = (the_point.x - r_tl) * dash_velocity;
 745                        } else {
 746                            dash_velocity = dv_b;
 747                            t = upto_bl - (the_point.x - r_bl) * dash_velocity;
 748                        }
 749                    } else {
 750                        if (center_to_point.x < 0.0) {
 751                            dash_velocity = dv_l;
 752                            t = upto_tl - (the_point.y - r_tl) * dash_velocity;
 753                        } else {
 754                            dash_velocity = dv_r;
 755                            t = upto_r + (the_point.y - r_tr) * dash_velocity;
 756                        }
 757                    }
 758                }
 759            }
 760            float dash_length = dash_length_per_width / dash_period_per_width;
 761            float desired_dash_gap = dash_gap_per_width / dash_period_per_width;
 762
 763            // Straight borders should start and end with a dash, so max_t is
 764            // reduced to cause this.
 765            max_t -= unrounded ? dash_length : 0.0;
 766            if (max_t >= 1.0) {
 767                // Adjust dash gap to evenly divide max_t
 768                float dash_count = floor(max_t);
 769                float dash_period = max_t / dash_count;
 770                border_color.a *= dash_alpha(t, dash_period, dash_length, dash_velocity, antialias_threshold);
 771            } else if (unrounded) {
 772                // When there isn't enough space for the full gap between the
 773                // two start / end dashes of a straight border, reduce gap to
 774                // make them fit.
 775                float dash_gap = max_t - dash_length;
 776                if (dash_gap > 0.0) {
 777                    float dash_period = dash_length + dash_gap;
 778                    border_color.a *= dash_alpha(t, dash_period, dash_length, dash_velocity, antialias_threshold);
 779                }
 780            }
 781        }
 782
 783        // Blend the border on top of the background and then linearly interpolate
 784        // between the two as we slide inside the background.
 785        float4 blended_border = over(background_color, border_color);
 786        color = lerp(background_color, blended_border,
 787                    saturate(antialias_threshold - inner_sdf));
 788    }
 789
 790    return color * float4(1.0, 1.0, 1.0, saturate(antialias_threshold - outer_sdf));
 791}
 792
 793/*
 794**
 795**              Shadows
 796**
 797*/
 798
 799struct Shadow {
 800    uint order;
 801    float blur_radius;
 802    Bounds bounds;
 803    Corners corner_radii;
 804    Bounds content_mask;
 805    Hsla color;
 806};
 807
 808struct ShadowVertexOutput {
 809    nointerpolation uint shadow_id: TEXCOORD0;
 810    float4 position: SV_Position;
 811    nointerpolation float4 color: COLOR;
 812    float4 clip_distance: SV_ClipDistance;
 813};
 814
 815struct ShadowFragmentInput {
 816  nointerpolation uint shadow_id: TEXCOORD0;
 817  float4 position: SV_Position;
 818  nointerpolation float4 color: COLOR;
 819};
 820
 821StructuredBuffer<Shadow> shadows: register(t1);
 822
 823ShadowVertexOutput shadow_vertex(uint vertex_id: SV_VertexID, uint shadow_id: SV_InstanceID) {
 824    float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
 825    Shadow shadow = shadows[shadow_id];
 826
 827    float margin = 3.0 * shadow.blur_radius;
 828    Bounds bounds = shadow.bounds;
 829    bounds.origin -= margin;
 830    bounds.size += 2.0 * margin;
 831
 832    float4 device_position = to_device_position(unit_vertex, bounds);
 833    float4 clip_distance = distance_from_clip_rect(unit_vertex, bounds, shadow.content_mask);
 834    float4 color = hsla_to_rgba(shadow.color);
 835
 836    ShadowVertexOutput output;
 837    output.position = device_position;
 838    output.color = color;
 839    output.shadow_id = shadow_id;
 840    output.clip_distance = clip_distance;
 841
 842    return output;
 843}
 844
 845float4 shadow_fragment(ShadowFragmentInput input): SV_TARGET {
 846    Shadow shadow = shadows[input.shadow_id];
 847
 848    float2 half_size = shadow.bounds.size / 2.;
 849    float2 center = shadow.bounds.origin + half_size;
 850    float2 point0 = input.position.xy - center;
 851    float corner_radius = pick_corner_radius(point0, shadow.corner_radii);
 852
 853    // The signal is only non-zero in a limited range, so don't waste samples
 854    float low = point0.y - half_size.y;
 855    float high = point0.y + half_size.y;
 856    float start = clamp(-3. * shadow.blur_radius, low, high);
 857    float end = clamp(3. * shadow.blur_radius, low, high);
 858
 859    // Accumulate samples (we can get away with surprisingly few samples)
 860    float step = (end - start) / 4.;
 861    float y = start + step * 0.5;
 862    float alpha = 0.;
 863    for (int i = 0; i < 4; i++) {
 864        alpha += blur_along_x(point0.x, point0.y - y, shadow.blur_radius,
 865                            corner_radius, half_size) *
 866                gaussian(y, shadow.blur_radius) * step;
 867        y += step;
 868    }
 869
 870    return input.color * float4(1., 1., 1., alpha);
 871}
 872
 873/*
 874**
 875**              Path Rasterization
 876**
 877*/
 878
 879struct PathRasterizationSprite {
 880    float2 xy_position;
 881    float2 st_position;
 882    Background color;
 883    Bounds bounds;
 884};
 885
 886StructuredBuffer<PathRasterizationSprite> path_rasterization_sprites: register(t1);
 887
 888struct PathVertexOutput {
 889    float4 position: SV_Position;
 890    float2 st_position: TEXCOORD0;
 891    nointerpolation uint vertex_id: TEXCOORD1;
 892    float4 clip_distance: SV_ClipDistance;
 893};
 894
 895struct PathFragmentInput {
 896    float4 position: SV_Position;
 897    float2 st_position: TEXCOORD0;
 898    nointerpolation uint vertex_id: TEXCOORD1;
 899};
 900
 901PathVertexOutput path_rasterization_vertex(uint vertex_id: SV_VertexID) {
 902    PathRasterizationSprite sprite = path_rasterization_sprites[vertex_id];
 903
 904    PathVertexOutput output;
 905    output.position = to_device_position_impl(sprite.xy_position);
 906    output.st_position = sprite.st_position;
 907    output.vertex_id = vertex_id;
 908    output.clip_distance = distance_from_clip_rect_impl(sprite.xy_position, sprite.bounds);
 909
 910    return output;
 911}
 912
 913float4 path_rasterization_fragment(PathFragmentInput input): SV_Target {
 914    float2 dx = ddx(input.st_position);
 915    float2 dy = ddy(input.st_position);
 916    PathRasterizationSprite sprite = path_rasterization_sprites[input.vertex_id];
 917
 918    Background background = sprite.color;
 919    Bounds bounds = sprite.bounds;
 920
 921    float alpha;
 922    if (length(float2(dx.x, dy.x))) {
 923        alpha = 1.0;
 924    } else {
 925        float2 gradient = 2.0 * input.st_position.xx * float2(dx.x, dy.x) - float2(dx.y, dy.y);
 926        float f = input.st_position.x * input.st_position.x - input.st_position.y;
 927        float distance = f / length(gradient);
 928        alpha = saturate(0.5 - distance);
 929    }
 930
 931    GradientColor gradient = prepare_gradient_color(
 932        background.tag, background.color_space, background.solid, background.colors);
 933
 934    float4 color = gradient_color(background, input.position.xy, bounds,
 935        gradient.solid, gradient.color0, gradient.color1);
 936    return float4(color.rgb * color.a * alpha, alpha * color.a);
 937}
 938
 939/*
 940**
 941**              Path Sprites
 942**
 943*/
 944
 945struct PathSprite {
 946    Bounds bounds;
 947};
 948
 949struct PathSpriteVertexOutput {
 950    float4 position: SV_Position;
 951    float2 texture_coords: TEXCOORD0;
 952};
 953
 954StructuredBuffer<PathSprite> path_sprites: register(t1);
 955
 956PathSpriteVertexOutput path_sprite_vertex(uint vertex_id: SV_VertexID, uint sprite_id: SV_InstanceID) {
 957    float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
 958    PathSprite sprite = path_sprites[sprite_id];
 959
 960    // Don't apply content mask because it was already accounted for when rasterizing the path
 961    float4 device_position = to_device_position(unit_vertex, sprite.bounds);
 962
 963    float2 screen_position = sprite.bounds.origin + unit_vertex * sprite.bounds.size;
 964    float2 texture_coords = screen_position / global_viewport_size;
 965
 966    PathSpriteVertexOutput output;
 967    output.position = device_position;
 968    output.texture_coords = texture_coords;
 969    return output;
 970}
 971
 972float4 path_sprite_fragment(PathSpriteVertexOutput input): SV_Target {
 973    return t_sprite.Sample(s_sprite, input.texture_coords);
 974}
 975
 976/*
 977**
 978**              Underlines
 979**
 980*/
 981
 982struct Underline {
 983    uint order;
 984    uint pad;
 985    Bounds bounds;
 986    Bounds content_mask;
 987    Hsla color;
 988    float thickness;
 989    uint wavy;
 990};
 991
 992struct UnderlineVertexOutput {
 993  nointerpolation uint underline_id: TEXCOORD0;
 994  float4 position: SV_Position;
 995  nointerpolation float4 color: COLOR;
 996  float4 clip_distance: SV_ClipDistance;
 997};
 998
 999struct UnderlineFragmentInput {
1000  nointerpolation uint underline_id: TEXCOORD0;
1001  float4 position: SV_Position;
1002  nointerpolation float4 color: COLOR;
1003};
1004
1005StructuredBuffer<Underline> underlines: register(t1);
1006
1007UnderlineVertexOutput underline_vertex(uint vertex_id: SV_VertexID, uint underline_id: SV_InstanceID) {
1008    float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
1009    Underline underline = underlines[underline_id];
1010    float4 device_position = to_device_position(unit_vertex, underline.bounds);
1011    float4 clip_distance = distance_from_clip_rect(unit_vertex, underline.bounds,
1012                                                    underline.content_mask);
1013    float4 color = hsla_to_rgba(underline.color);
1014
1015    UnderlineVertexOutput output;
1016    output.position = device_position;
1017    output.color = color;
1018    output.underline_id = underline_id;
1019    output.clip_distance = clip_distance;
1020    return output;
1021}
1022
1023float4 underline_fragment(UnderlineFragmentInput input): SV_Target {
1024    const float WAVE_FREQUENCY = 2.0;
1025    const float WAVE_HEIGHT_RATIO = 0.8;
1026
1027    Underline underline = underlines[input.underline_id];
1028    if (underline.wavy) {
1029        float half_thickness = underline.thickness * 0.5;
1030        float2 origin = underline.bounds.origin;
1031
1032        float2 st = ((input.position.xy - origin) / underline.bounds.size.y) - float2(0., 0.5);
1033        float frequency = (M_PI_F * WAVE_FREQUENCY * underline.thickness) / underline.bounds.size.y;
1034        float amplitude = (underline.thickness * WAVE_HEIGHT_RATIO) / underline.bounds.size.y;
1035
1036        float sine = sin(st.x * frequency) * amplitude;
1037        float dSine = cos(st.x * frequency) * amplitude * frequency;
1038        float distance = (st.y - sine) / sqrt(1. + dSine * dSine);
1039        float distance_in_pixels = distance * underline.bounds.size.y;
1040        float distance_from_top_border = distance_in_pixels - half_thickness;
1041        float distance_from_bottom_border = distance_in_pixels + half_thickness;
1042        float alpha = saturate(
1043            0.5 - max(-distance_from_bottom_border, distance_from_top_border));
1044        return input.color * float4(1., 1., 1., alpha);
1045    } else {
1046        return input.color;
1047    }
1048}
1049
1050/*
1051**
1052**              Monochrome sprites
1053**
1054*/
1055
1056struct MonochromeSprite {
1057    uint order;
1058    uint pad;
1059    Bounds bounds;
1060    Bounds content_mask;
1061    Hsla color;
1062    AtlasTile tile;
1063    TransformationMatrix transformation;
1064};
1065
1066struct MonochromeSpriteVertexOutput {
1067    float4 position: SV_Position;
1068    float2 tile_position: POSITION;
1069    nointerpolation float4 color: COLOR;
1070    float4 clip_distance: SV_ClipDistance;
1071};
1072
1073struct MonochromeSpriteFragmentInput {
1074    float4 position: SV_Position;
1075    float2 tile_position: POSITION;
1076    nointerpolation float4 color: COLOR;
1077    float4 clip_distance: SV_ClipDistance;
1078};
1079
1080StructuredBuffer<MonochromeSprite> mono_sprites: register(t1);
1081
1082MonochromeSpriteVertexOutput monochrome_sprite_vertex(uint vertex_id: SV_VertexID, uint sprite_id: SV_InstanceID) {
1083    float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
1084    MonochromeSprite sprite = mono_sprites[sprite_id];
1085    float4 device_position =
1086        to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation);
1087    float4 clip_distance = distance_from_clip_rect(unit_vertex, sprite.bounds, sprite.content_mask);
1088    float2 tile_position = to_tile_position(unit_vertex, sprite.tile);
1089    float4 color = hsla_to_rgba(sprite.color);
1090
1091    MonochromeSpriteVertexOutput output;
1092    output.position = device_position;
1093    output.tile_position = tile_position;
1094    output.color = color;
1095    output.clip_distance = clip_distance;
1096    return output;
1097}
1098
1099float4 monochrome_sprite_fragment(MonochromeSpriteFragmentInput input): SV_Target {
1100    float sample = t_sprite.Sample(s_sprite, input.tile_position).r;
1101    return float4(input.color.rgb, input.color.a * sample);
1102}
1103
1104/*
1105**
1106**              Polychrome sprites
1107**
1108*/
1109
1110struct PolychromeSprite {
1111    uint order;
1112    uint pad;
1113    uint grayscale;
1114    float opacity;
1115    Bounds bounds;
1116    Bounds content_mask;
1117    Corners corner_radii;
1118    AtlasTile tile;
1119};
1120
1121struct PolychromeSpriteVertexOutput {
1122    nointerpolation uint sprite_id: TEXCOORD0;
1123    float4 position: SV_Position;
1124    float2 tile_position: POSITION;
1125    float4 clip_distance: SV_ClipDistance;
1126};
1127
1128struct PolychromeSpriteFragmentInput {
1129    nointerpolation uint sprite_id: TEXCOORD0;
1130    float4 position: SV_Position;
1131    float2 tile_position: POSITION;
1132};
1133
1134StructuredBuffer<PolychromeSprite> poly_sprites: register(t1);
1135
1136PolychromeSpriteVertexOutput polychrome_sprite_vertex(uint vertex_id: SV_VertexID, uint sprite_id: SV_InstanceID) {
1137    float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
1138    PolychromeSprite sprite = poly_sprites[sprite_id];
1139    float4 device_position = to_device_position(unit_vertex, sprite.bounds);
1140    float4 clip_distance = distance_from_clip_rect(unit_vertex, sprite.bounds,
1141                                                    sprite.content_mask);
1142    float2 tile_position = to_tile_position(unit_vertex, sprite.tile);
1143
1144    PolychromeSpriteVertexOutput output;
1145    output.position = device_position;
1146    output.tile_position = tile_position;
1147    output.sprite_id = sprite_id;
1148    output.clip_distance = clip_distance;
1149    return output;
1150}
1151
1152float4 polychrome_sprite_fragment(PolychromeSpriteFragmentInput input): SV_Target {
1153    PolychromeSprite sprite = poly_sprites[input.sprite_id];
1154    float4 sample = t_sprite.Sample(s_sprite, input.tile_position);
1155    float distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii);
1156
1157    float4 color = sample;
1158    if ((sprite.grayscale & 0xFFu) != 0u) {
1159        float3 grayscale = dot(color.rgb, GRAYSCALE_FACTORS);
1160        color = float4(grayscale, sample.a);
1161    }
1162    color.a *= sprite.opacity * saturate(0.5 - distance);
1163    return color;
1164}