Skip to repository content

tenant.openagents/omega

No repository description is available.

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

shaders.metal

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