lurq 0.41.2

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
// Rounded-corner quad pipeline (elliptical, optional ring).
//
// Vertex buffer 0 (per-vertex):  unit quad corner in [0,1]^2.
// Vertex buffer 1 (per-instance): pos / size in pixels, linear RGBA color,
//                                 horizontal corner radii (TL, TR, BR, BL),
//                                 vertical corner radii (same order),
//                                 per-side ring thickness (top, right,
//                                 bottom, left).
// Bind group 0 / binding 0: viewport size in pixels.
//
// Two modes selected by whether any stroke component is > 0:
//   - Filled:    paint the entire (rounded) box with `color`.
//   - Stroked:   paint only the ring between the outer rounded box and
//                an inner rounded box inset on each side by the matching
//                stroke width.
// In both modes a ~1-pixel anti-alias band keeps edges smooth.
//
// Box-shadow instances (no stroke, `pattern.x` = 1 outer / 2 inset) paint a
// Gaussian-blurred rounded rect instead; see `box_shadow_alpha`. For them
// `radii_h` are the element box's radii, `radii_v` the shadow shape's,
// `pattern.yz` the shape offset, `pattern.w` the spread and `shadow_sigma`
// the Gaussian's standard deviation.
//
// The corner zone uses a gradient-corrected ellipse SDF so corners can
// be elliptical (h != v); when h == v it reduces to the usual circular
// case.

// `Globals` is a per-clip-range uniform block — `prepare` writes one
// entry per `DisplayList::clips` slot and `record` rebinds it via a
// dynamic offset. Vertex stage reads `viewport.xy` for NDC mapping;
// fragment stage uses `clip_*` to discard fragments outside the
// active rounded clip.
struct Globals {
    viewport:     vec4<f32>,
    clip_rect:    vec4<f32>,   // x, y, w, h
    clip_radii_h: vec4<f32>,
    clip_radii_v: vec4<f32>,
    clip_active:  vec4<f32>,   // x = 1.0 to enable SDF discard
};

@group(0) @binding(0) var<uniform> globals: Globals;
@group(0) @binding(1) var<storage, read> gradients: array<vec4<f32>>;

struct VsIn {
    @location(0) corner:     vec2<f32>,
    @location(1) pos:        vec2<f32>,
    @location(2) size:       vec2<f32>,
    @location(3) color:      vec4<f32>,
    @location(4) radii_h:    vec4<f32>,  // TL, TR, BR, BL
    @location(5) radii_v:    vec4<f32>,  // TL, TR, BR, BL
    @location(6) stroke:     vec4<f32>,  // top, right, bottom, left
    @location(7) pattern:    vec4<f32>,  // kind, dash, gap, _
    @location(8) transform:     vec4<f32>,  // 2x2 matrix: a, b, c, d
    @location(9) xf_origin:    vec2<f32>,  // transform origin relative to rect top-left
    @location(10) shadow_sigma: f32,
    @location(11) gradient_offset: f32,
};

struct VsOut {
    @builtin(position) clip:      vec4<f32>,
    @location(0)       color:     vec4<f32>,
    /// Pixel offset from the box's centre.
    @location(1)       local:     vec2<f32>,
    @location(2)       half_size: vec2<f32>,
    @location(3)       radii_h:   vec4<f32>,
    @location(4)       radii_v:   vec4<f32>,
    @location(5)       stroke:       vec4<f32>,
    @location(6)       pattern:      vec4<f32>,
    @location(7)       shadow_sigma: f32,
    @location(8)       gradient_offset: f32,
};

@vertex
fn vs_main(in: VsIn) -> VsOut {
    // Local position within the quad (before transform). The mesh is
    // expanded slightly so transformed edges have fragments on both
    // sides of the SDF boundary; otherwise the rasterizer clips away
    // the outer half of the AA band.
    var aa_outset = 2.0;
    let max_stroke = max(max(in.stroke.x, in.stroke.y), max(in.stroke.z, in.stroke.w));
    if (max_stroke <= 0.0 && in.pattern.x > 0.5 && in.pattern.x < 1.5) {
        // An outer shadow paints beyond its element box.
        aa_outset = aa_outset + max(in.pattern.w, 0.0) + max(abs(in.pattern.y), abs(in.pattern.z))
            + SHADOW_EXTENT_SIGMAS * in.shadow_sigma;
    }
    let local_px = in.corner * (in.size + vec2<f32>(aa_outset * 2.0, aa_outset * 2.0))
                 - vec2<f32>(aa_outset, aa_outset);
    // Apply 2x2 transform around xf_origin.
    let centered = local_px - in.xf_origin;
    let rotated = vec2<f32>(
        in.transform.x * centered.x + in.transform.z * centered.y,
        in.transform.y * centered.x + in.transform.w * centered.y,
    );
    let px = in.pos + rotated + in.xf_origin;

    // `viewport.zw` is the target's origin in window pixels (non-zero when
    // painting into an opacity layer).
    let viewport = globals.viewport.xy;
    let target_px = px - globals.viewport.zw;
    let ndc = vec2<f32>(
        (target_px.x / viewport.x) * 2.0 - 1.0,
        1.0 - (target_px.y / viewport.y) * 2.0,
    );

    var out: VsOut;
    out.clip      = vec4<f32>(ndc, 0.0, 1.0);
    out.color     = in.color;
    out.half_size = in.size * 0.5;
    // SDF local coords stay in un-rotated quad space.
    out.local     = local_px - in.size * 0.5;
    out.radii_h   = in.radii_h;
    out.radii_v   = in.radii_v;
    out.stroke       = in.stroke;
    out.pattern      = in.pattern;
    out.shadow_sigma     = in.shadow_sigma;
    out.gradient_offset  = in.gradient_offset;
    return out;
}

/// Arc-length along the outline of a uniform-radius rounded box, from
/// the start of the side's 45° wedge to the projection of `p` onto the
/// outline. Only used for one-sided rings with a dash/dot pattern.
///
/// `side_idx`: 0 = top, 1 = right, 2 = bottom, 3 = left.
/// `r`:        circular corner radius (assumes h == v on every corner).
///
/// Each side spans: half of the entering corner arc + the straight
/// edge + half of the exiting corner arc. The result is in pixels and
/// monotonically increases as we walk the outline within the wedge.
fn perimeter_param(p: vec2<f32>, hs: vec2<f32>, r: f32, side_idx: i32) -> f32 {
    let pi = 3.14159265359;
    let quarter = pi * r * 0.5;
    let half_quarter = quarter * 0.5;

    // Map the fragment into the canonical "top side" frame so we only
    // implement the geometry once. After this swap, `q` is in the same
    // coordinate space as if `side_idx` were 0 (top), and the entering
    // corner is at the top-left, exiting corner at the top-right.
    var q: vec2<f32>;
    var sz: vec2<f32>;
    switch side_idx {
        case 0: { q = p;                              sz = hs;                          }
        case 1: { q = vec2<f32>( p.y,        -p.x);   sz = vec2<f32>(hs.y, hs.x);       }
        case 2: { q = vec2<f32>(-p.x,        -p.y);   sz = hs;                          }
        case 3: { q = vec2<f32>(-p.y,         p.x);   sz = vec2<f32>(hs.y, hs.x);       }
        default: { q = p; sz = hs; }
    }

    let straight_len = max(2.0 * sz.x - 2.0 * r, 0.0);
    let total = half_quarter + straight_len + half_quarter;

    // Entering corner zone: q.x < -sz.x + r AND q.y near top.
    let left_corner = vec2<f32>(-sz.x + r, -sz.y + r);
    let right_corner = vec2<f32>(sz.x - r, -sz.y + r);

    if (q.x < left_corner.x) {
        // Top half of TL arc. Theta sweeps from -3π/4 (wedge boundary)
        // to -π/2 (top tangent). Param goes 0 → half_quarter.
        let v = q - left_corner;
        let theta = atan2(v.y, v.x);
        let t = clamp(theta - (-0.75 * pi), 0.0, 0.25 * pi);
        return t * r;
    } else if (q.x > right_corner.x) {
        // Top half of TR arc. Theta sweeps from -π/2 to -π/4.
        let v = q - right_corner;
        let theta = atan2(v.y, v.x);
        let t = clamp(theta - (-0.5 * pi), 0.0, 0.25 * pi);
        return half_quarter + straight_len + t * r;
    }
    // Straight portion of the top edge.
    let s = clamp(q.x - left_corner.x, 0.0, straight_len);
    return half_quarter + s;
}

/// Pick the (h, v) radius pair for whichever quadrant `p` lies in.
/// Order: TL, TR, BR, BL (matches CSS `border-radius` longhand order).
fn pick_radius(p: vec2<f32>, rh: vec4<f32>, rv: vec4<f32>) -> vec2<f32> {
    if (p.y < 0.0) {
        if (p.x < 0.0) { return vec2<f32>(rh.x, rv.x); } // TL
        else           { return vec2<f32>(rh.y, rv.y); } // TR
    } else {
        if (p.x < 0.0) { return vec2<f32>(rh.w, rv.w); } // BL
        else           { return vec2<f32>(rh.z, rv.z); } // BR
    }
}

/// SDF of a box with elliptical corners (radius `r = (rx, ry)` per
/// quadrant). `p` is centre-relative pixel coords; `half_size` is the
/// box half-extent.
///
/// - Corner zone (both q components > 0) → gradient-corrected ellipse
///   SDF. Reduces to the exact circular formula `length(q) - r` when
///   rx == ry; smooth approximation otherwise.
/// - Edge band / interior → rectangle distance with the corner radii
///   subtracted on each axis: `max(q.x - rx, q.y - ry)`.
fn sd_rounded_box(p: vec2<f32>, half_size: vec2<f32>, r: vec2<f32>) -> f32 {
    let safe_r = max(r, vec2<f32>(0.0, 0.0));
    let q = abs(p) - half_size + safe_r;

    if (q.x > 0.0 && q.y > 0.0) {
        // Corner zone.
        if (safe_r.x <= 0.0 || safe_r.y <= 0.0) {
            return max(q.x, q.y);
        }
        let pn = q / safe_r;
        let l = length(pn);
        if (l <= 1e-6) {
            return -min(safe_r.x, safe_r.y);
        }
        let g = max(length(pn / safe_r), 1e-6);
        // Euclidean distance estimate = (length(pn) - 1) / |grad|, where
        // |grad| = length(pn / r) / length(pn). The factor of `l` in the
        // numerator below absorbs the `length(pn)` in the denominator
        // of |grad|. Reduces to `length(q) - r` for circular corners.
        return (l - 1.0) * l / g;
    }

    // Edge band or interior. The `- safe_r.{x,y}` subtraction undoes the
    // `+ safe_r` we added when computing `q`, which keeps the corner
    // zone consistent with the rounded-box shape.
    return max(q.x - safe_r.x, q.y - safe_r.y);
}

fn aa_width(d: f32) -> f32 {
    return max(fwidth(d), 1.0);
}

/// Ramp width for one of the four half-pixel subsamples below. Each
/// subsample stands for a 0.5 px square, so its ramp is half a pixel wide:
/// a full-pixel ramp per subsample blurred every edge twice, leaving pixels
/// fully inside an axis-aligned edge at 87.5% coverage and bleeding 12.5%
/// into the pixel outside (a faint line against the clear colour at the
/// window edge).
fn subsample_aa_width(d: f32) -> f32 {
    return 0.5 * aa_width(d);
}

fn rounded_fill_alpha(local: vec2<f32>, half_size: vec2<f32>, radii_h: vec4<f32>, radii_v: vec4<f32>) -> f32 {
    let radius = pick_radius(local, radii_h, radii_v);
    let dist = sd_rounded_box(local, half_size, radius);
    return clamp(0.5 - dist / subsample_aa_width(dist), 0.0, 1.0);
}

fn rounded_stroke_alpha(
    local: vec2<f32>,
    half_size: vec2<f32>,
    radii_h: vec4<f32>,
    radii_v: vec4<f32>,
    stroke: vec4<f32>,
    max_stroke: f32,
) -> f32 {
    let radius = pick_radius(local, radii_h, radii_v);
    let outer_dist = sd_rounded_box(local, half_size, radius);
    let inner_half = max(vec2<f32>(
        half_size.x - 0.5 * (stroke.y + stroke.w),
        half_size.y - 0.5 * (stroke.x + stroke.z),
    ), vec2<f32>(0.0, 0.0));
    let inner_centre = vec2<f32>(
        0.5 * (stroke.w - stroke.y),
        0.5 * (stroke.x - stroke.z),
    );
    let inner_r = vec2<f32>(
        max(0.0, radius.x - max_stroke),
        max(0.0, radius.y - max_stroke),
    );
    let inner_dist = sd_rounded_box(local - inner_centre, inner_half, inner_r);
    let dist = max(outer_dist, -inner_dist);
    return clamp(0.5 - dist / subsample_aa_width(dist), 0.0, 1.0);
}

fn supersampled_fill_alpha(local: vec2<f32>, half_size: vec2<f32>, radii_h: vec4<f32>, radii_v: vec4<f32>) -> f32 {
    return (
        rounded_fill_alpha(local + vec2<f32>(-0.25, -0.25), half_size, radii_h, radii_v) +
        rounded_fill_alpha(local + vec2<f32>(0.25, -0.25), half_size, radii_h, radii_v) +
        rounded_fill_alpha(local + vec2<f32>(-0.25, 0.25), half_size, radii_h, radii_v) +
        rounded_fill_alpha(local + vec2<f32>(0.25, 0.25), half_size, radii_h, radii_v)
    ) * 0.25;
}

fn supersampled_stroke_alpha(
    local: vec2<f32>,
    half_size: vec2<f32>,
    radii_h: vec4<f32>,
    radii_v: vec4<f32>,
    stroke: vec4<f32>,
    max_stroke: f32,
) -> f32 {
    return (
        rounded_stroke_alpha(local + vec2<f32>(-0.25, -0.25), half_size, radii_h, radii_v, stroke, max_stroke) +
        rounded_stroke_alpha(local + vec2<f32>(0.25, -0.25), half_size, radii_h, radii_v, stroke, max_stroke) +
        rounded_stroke_alpha(local + vec2<f32>(-0.25, 0.25), half_size, radii_h, radii_v, stroke, max_stroke) +
        rounded_stroke_alpha(local + vec2<f32>(0.25, 0.25), half_size, radii_h, radii_v, stroke, max_stroke)
    ) * 0.25;
}

// Box shadows. The same formula as `blurred_rounded_rect_coverage` in
// `layout/box_shadow.rs` and `quad.hlsl`; keep the three in step.
const SHADOW_Y_SAMPLES: i32 = 8;
const SHADOW_EXTENT_SIGMAS: f32 = 3.0;
const SHADOW_MIN_SIGMA: f32 = 0.1;

fn shadow_erf(x: vec2<f32>) -> vec2<f32> {
    let s = sign(x);
    let a = abs(x);
    var r = 1.0 + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;
    r = r * r;
    return s - s / (r * r);
}

fn shadow_gaussian(x: f32, sigma: f32) -> f32 {
    return exp(-(x * x) / (2.0 * sigma * sigma)) / (2.5066283 * sigma);
}

/// A row of the rounded rect at height `y`, convolved along x with the
/// Gaussian: the difference of two `erf`s at the row's curved ends.
fn shadow_blur_along_x(x: f32, y: f32, sigma: f32, corner: f32, half: vec2<f32>) -> f32 {
    let delta = min(half.y - corner - abs(y), 0.0);
    let curved = half.x - corner + sqrt(max(corner * corner - delta * delta, 0.0));
    let integral = 0.5 + 0.5 * shadow_erf((vec2<f32>(x, x) + vec2<f32>(-curved, curved)) * (0.70710678 / sigma));
    return integral.y - integral.x;
}

/// Coverage of a rounded rect (half extent `half`, circular corner `radii`)
/// blurred by `sigma`, at centre-relative `p`; the y convolution is a
/// midpoint sum over +/- 3 sigma.
fn blurred_rounded_box(p: vec2<f32>, half: vec2<f32>, radii: vec4<f32>, sigma: f32) -> f32 {
    if (half.x <= 0.0 || half.y <= 0.0) {
        return 0.0;
    }
    let corner = max(min(pick_radius(p, radii, radii).x, min(half.x, half.y)), 0.0);
    let extent = SHADOW_EXTENT_SIGMAS * sigma;
    let start = clamp(-extent, p.y - half.y, p.y + half.y);
    let end = clamp(extent, p.y - half.y, p.y + half.y);
    let step = (end - start) / f32(SHADOW_Y_SAMPLES);
    var y = start + step * 0.5;
    var coverage = 0.0;
    for (var i: i32 = 0; i < SHADOW_Y_SAMPLES; i = i + 1) {
        coverage = coverage + shadow_blur_along_x(p.x, p.y - y, sigma, corner, half) * shadow_gaussian(y, sigma) * step;
        y = y + step;
    }
    return clamp(coverage, 0.0, 1.0);
}

fn shadow_shape_alpha(p: vec2<f32>, half: vec2<f32>, radii: vec4<f32>, sigma: f32) -> f32 {
    if (sigma < SHADOW_MIN_SIGMA) {
        if (half.x <= 0.0 || half.y <= 0.0) {
            return 0.0;
        }
        return supersampled_fill_alpha(p, half, radii, radii);
    }
    return blurred_rounded_box(p, half, radii, sigma);
}

/// An outer shadow covers its shape outside the element box; an inset one
/// covers the box outside its shape.
fn box_shadow_alpha(
    local: vec2<f32>,
    half_size: vec2<f32>,
    box_radii: vec4<f32>,
    shape_radii: vec4<f32>,
    params: vec4<f32>,
    sigma: f32,
) -> f32 {
    let offset = params.yz;
    let spread = params.w;
    let box_alpha = supersampled_fill_alpha(local, half_size, box_radii, box_radii);
    if (params.x < 1.5) {
        let shape_half = max(half_size + vec2<f32>(spread, spread), vec2<f32>(0.0, 0.0));
        return shadow_shape_alpha(local - offset, shape_half, shape_radii, sigma) * (1.0 - box_alpha);
    }
    let shape_half = max(half_size - vec2<f32>(spread, spread), vec2<f32>(0.0, 0.0));
    return box_alpha * (1.0 - shadow_shape_alpha(local - offset, shape_half, shape_radii, sigma));
}

/// Evaluate a CSS-like gradient for a fragment at centre-relative pixel
/// `local`, within a box of half-extent `half`. `off` is the vec4 index of
/// the gradient header in the `gradients` storage buffer. Layout:
///   [count, kind, flags, from_angle]
///   [dir.x, dir.y, center.x, center.y]
///   then per stop: [r, g, b, a], [position, _, _, _]
/// kind: 0 = linear, 1 = radial (flags bit0 = ellipse), 2 = conic.
fn sample_gradient(off: i32, local: vec2<f32>, half: vec2<f32>) -> vec4<f32> {
    let h0 = gradients[off];
    let h1 = gradients[off + 1];
    let count = i32(h0.x);
    let kind = i32(h0.y);
    let pi = 3.14159265359;

    var t: f32;
    if (kind == 0) {
        // Linear: project onto the unit direction, normalized by half the
        // gradient-line length so 0/1 reach the corners (CSS behaviour).
        let dir = h1.xy;
        let hl = abs(half.x * dir.x) + abs(half.y * dir.y);
        t = (dot(local, dir) + hl) / (2.0 * max(hl, 1e-5));
    } else if (kind == 1) {
        // Radial, farthest-corner.
        let center = (h1.zw * 2.0 - vec2<f32>(1.0, 1.0)) * half;
        if (h0.z > 0.5) {
            // Ellipse fitted to the box.
            let cn = h1.zw * 2.0 - vec2<f32>(1.0, 1.0);
            let p = (local - center) / max(half, vec2<f32>(1e-3, 1e-3));
            let radius = max(
                max(length(vec2<f32>(-1.0, -1.0) - cn), length(vec2<f32>(1.0, -1.0) - cn)),
                max(length(vec2<f32>(-1.0, 1.0) - cn), length(vec2<f32>(1.0, 1.0) - cn)),
            );
            t = length(p) / max(radius, 1e-5);
        } else {
            let radius = max(
                max(length(vec2<f32>(-half.x, -half.y) - center), length(vec2<f32>(half.x, -half.y) - center)),
                max(length(vec2<f32>(-half.x, half.y) - center), length(vec2<f32>(half.x, half.y) - center)),
            );
            t = length(local - center) / max(radius, 1e-5);
        }
    } else {
        // Conic: angle clockwise from the top.
        let center = (h1.zw * 2.0 - vec2<f32>(1.0, 1.0)) * half;
        let d = local - center;
        let ang = (atan2(d.x, -d.y) - h0.w) / (2.0 * pi);
        t = ang - floor(ang);
    }

    if (kind != 2) {
        t = clamp(t, 0.0, 1.0);
    }

    let stop_base = off + 2;
    let last = count - 1;
    var color = gradients[stop_base + 2 * last];
    for (var i: i32 = 0; i < last; i = i + 1) {
        let pb = gradients[stop_base + 2 * (i + 1) + 1].x;
        if (t <= pb) {
            let pa = gradients[stop_base + 2 * i + 1].x;
            let ca = gradients[stop_base + 2 * i];
            let cb = gradients[stop_base + 2 * (i + 1)];
            let span = max(pb - pa, 1e-5);
            color = mix(ca, cb, clamp((t - pa) / span, 0.0, 1.0));
            break;
        }
    }
    return color;
}

/// Count how many sides have a positive stroke width.
fn nonzero_side_count(s: vec4<f32>) -> i32 {
    var n: i32 = 0;
    if (s.x > 0.0) { n = n + 1; }
    if (s.y > 0.0) { n = n + 1; }
    if (s.z > 0.0) { n = n + 1; }
    if (s.w > 0.0) { n = n + 1; }
    return n;
}

// The render target is not sRGB, so the fixed-function blend mixes
// sRGB-encoded values, as CSS and design tools do. `fs_main` works in linear
// light like the rest of the pipeline and encodes each result it returns.
fn encode_srgb(color: vec4<f32>) -> vec4<f32> {
    let c = clamp(color.rgb, vec3<f32>(0.0), vec3<f32>(1.0));
    let low = c * 12.92;
    let high = 1.055 * pow(c, vec3<f32>(1.0 / 2.4)) - 0.055;
    return vec4<f32>(select(high, low, c <= vec3<f32>(0.0031308)), color.a);
}

@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
    var clip_alpha = 1.0;
    // Rounded-clip discard. The active clip's rect + radii are
    // supplied by the per-range `Globals` uniform; we recover the
    // fragment's screen-space pixel position from the @builtin
    // (which the rasteriser fills as the un-normalised pixel
    // coord) and reuse the same SDF helper as the box itself uses
    // for its own corners.
    if (globals.clip_active.x > 0.5) {
        let frag_pos = in.clip.xy;
        let cr = globals.clip_rect;
        let half = vec2<f32>(cr.z, cr.w) * 0.5;
        let centre = vec2<f32>(cr.x + half.x, cr.y + half.y);
        let local_clip = frag_pos - centre;
        let r = pick_radius(local_clip, globals.clip_radii_h, globals.clip_radii_v);
        let d = sd_rounded_box(local_clip, half, r);
        let aa = aa_width(d);
        clip_alpha = clamp(0.5 - d / aa, 0.0, 1.0);
        if (clip_alpha <= 0.0) {
            discard;
        }
    }

    var base_color = in.color;
    if (in.gradient_offset >= 0.0) {
        let off = i32(in.gradient_offset + 0.5);
        if (i32(gradients[off].x) >= 1) {
            base_color = sample_gradient(off, in.local, in.half_size);
        }
    }

    let max_stroke = max(max(in.stroke.x, in.stroke.y), max(in.stroke.z, in.stroke.w));

    if (max_stroke <= 0.0) {
        if (in.pattern.x > 0.5) {
            let shadow_alpha = box_shadow_alpha(in.local, in.half_size, in.radii_h, in.radii_v, in.pattern, in.shadow_sigma);
            if (shadow_alpha <= 0.0) { discard; }
            return encode_srgb(vec4<f32>(base_color.rgb, base_color.a * shadow_alpha * clip_alpha));
        }
        let alpha = supersampled_fill_alpha(in.local, in.half_size, in.radii_h, in.radii_v);
        // Filled mode.
        if (alpha <= 0.0) { discard; }
        return encode_srgb(vec4<f32>(base_color.rgb, base_color.a * alpha * clip_alpha));
    }

    let nz = nonzero_side_count(in.stroke);
    let outer_r = pick_radius(in.local, in.radii_h, in.radii_v);
    let outer_dist = sd_rounded_box(in.local, in.half_size, outer_r);
    let inner_half = vec2<f32>(
        in.half_size.x - 0.5 * (in.stroke.y + in.stroke.w),
        in.half_size.y - 0.5 * (in.stroke.x + in.stroke.z),
    );
    let inner_centre = vec2<f32>(
        0.5 * (in.stroke.w - in.stroke.y),
        0.5 * (in.stroke.x - in.stroke.z),
    );

    let inner_r = vec2<f32>(
        max(0.0, outer_r.x - max_stroke),
        max(0.0, outer_r.y - max_stroke),
    );
    let inner_dist = sd_rounded_box(in.local - inner_centre, inner_half, inner_r);
    let dist = max(outer_dist, -inner_dist);
    let aa = aa_width(dist);

    var side_idx: i32 = -1;
    if (nz == 1) {
        if (in.stroke.x > 0.0) { side_idx = 0; } // top
        if (in.stroke.y > 0.0) { side_idx = 1; } // right
        if (in.stroke.z > 0.0) { side_idx = 2; } // bottom
        if (in.stroke.w > 0.0) { side_idx = 3; } // left
    }

    var alpha = supersampled_stroke_alpha(in.local, in.half_size, in.radii_h, in.radii_v, in.stroke, max_stroke);

    // Dash / dot modulation. Only meaningful on one-sided rings with a
    // uniform circular corner radius (h == v on every corner). Other
    // configurations leave the pattern unhonoured.
    let pattern_kind = in.pattern.x;
    if (side_idx >= 0 && pattern_kind > 0.5) {
        // Treat as circular if h ~= v on the relevant corners. Otherwise
        // keep solid.
        let r_max = max(max(in.radii_h.x, in.radii_h.y), max(in.radii_h.z, in.radii_h.w));
        let r_min = min(min(in.radii_h.x, in.radii_h.y), min(in.radii_h.z, in.radii_h.w));
        let v_max = max(max(in.radii_v.x, in.radii_v.y), max(in.radii_v.z, in.radii_v.w));
        let circular = abs(r_max - v_max) < 0.001 && abs(r_max - r_min) < 0.001;
        if (circular) {
            let r = r_max;
            let arc = perimeter_param(in.local, in.half_size, r, side_idx);
            let dash = max(in.pattern.y, 0.0001);
            let gap  = max(in.pattern.z, 0.0001);
            let period = dash + gap;
            let phase = arc - floor(arc / period) * period;
            let edge_aa = aa;
            // Smooth on at phase=0, smooth off at phase=dash.
            let dash_alpha = clamp(0.5 + (dash - phase) / edge_aa, 0.0, 1.0)
                           * clamp(0.5 + phase / edge_aa, 0.0, 1.0);
            alpha = alpha * dash_alpha;
        }
    }

    if (alpha <= 0.0) {
        discard;
    }
    return encode_srgb(vec4<f32>(base_color.rgb, base_color.a * alpha * clip_alpha));
}