frus-gpu 0.4.0

frus — GPU context and 2D rendering engine (Milestone 0)
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
// **Layer** compositing: a full-screen quad samples the layer's already-rendered
// texture and recomposes it at the group opacity, with clipping. The sample is
// already linear, the texture being sRGB, so nothing is converted back.
//
// A layer may also carry a **colour filter** and a **mask**, and those are applied
// here, between the sample and the composite. Both are defined on sRGB-encoded,
// straight-alpha values — the space colours are authored in — so the fragment
// un-premultiplies, converts to sRGB, filters, and puts it all back. With no filter
// that round trip is skipped entirely and the output is what it always was.
//
// The third effect, the image filter, is not here: it needs a pixel's neighbours,
// so it runs as a separate pre-pass over the layer texture before this one samples
// it (see `fx.wgsl`).

struct Viewport {
    size: vec2<f32>,
};

@group(0) @binding(0)
var<uniform> viewport: Viewport;

@group(1) @binding(0)
var tex: texture_2d<f32>;
@group(1) @binding(1)
var samp: sampler;
// The clip mask (ClipPath): the path rendered in white; solid white otherwise.
@group(1) @binding(2)
var mask: texture_2d<f32>;

// The layer's colour filter and shader mask. Per layer rather than per instance
// because a colour matrix alone is twenty numbers, and vertex attributes are a
// scarcer resource than a uniform slice: each layer already has its own bind group
// for its texture, so this rides along at no extra cost.
struct FilterParams {
    // (colour kind, mask kind, colour blend, mask blend). Colour kind: 0 none,
    // 1 matrix, 2 a colour blended in. Mask kind: 0 none, 1 linear, 2 radial.
    flags: vec4<f32>,
    // The colour matrix, row by row, then the constant column.
    m0: vec4<f32>,
    m1: vec4<f32>,
    m2: vec4<f32>,
    m3: vec4<f32>,
    m4: vec4<f32>,
    // The colour of a `Mode` colour fx.
    mode_color: vec4<f32>,
    // Linear: (from.x, from.y, to.x, to.y). Radial: (center.x, center.y, radius, _).
    mask_geom: vec4<f32>,
    mask_c0: vec4<f32>,
    mask_c1: vec4<f32>,
    // (blend mode + 1, _, _, _): how the layer meets what is under it; 0 paints it over
    // (milestone 646).
    blend: vec4<f32>,
};

@group(1) @binding(3)
var<uniform> fx: FilterParams;
// What is painted under the layer, for a layer that blends with it: a copy of the
// target so far. Opaque white for every other layer, and never read by them.
@group(1) @binding(4)
var under_tex: texture_2d<f32>;

struct VertexInput {
    @location(0) unit_pos: vec2<f32>,
};

struct InstanceInput {
    @location(1) clip: vec4<f32>,    // x, y, width, height (px)
    @location(2) inv_lin: vec4<f32>, // affine inverse, linear part: ia, ib, ic, id
    @location(3) inv_tr_op: vec4<f32>, // ie, if, opacity, _
    @location(4) shape: vec4<f32>,   // kind (0=rect,1=rrect,2=oval), _, _, _
    @location(5) radii: vec4<f32>,   // rrect radii: tl, tr, br, bl
    @location(6) region: vec4<f32>,  // where the texture lies: x, y, width, height (px)
};

struct VertexOutput {
    @builtin(position) clip_position: vec4<f32>,
    @location(0) uv: vec2<f32>,
    @location(1) frag_px: vec2<f32>,
    @location(2) @interpolate(flat) clip: vec4<f32>,
    @location(3) @interpolate(flat) opacity: f32,
    @location(4) @interpolate(flat) inv_lin: vec4<f32>,
    @location(5) @interpolate(flat) inv_tr: vec2<f32>,
    @location(6) @interpolate(flat) shape: vec4<f32>,
    @location(7) @interpolate(flat) radii: vec4<f32>,
    @location(8) @interpolate(flat) region: vec4<f32>,
};

@vertex
fn vs_main(vert: VertexInput, inst: InstanceInput) -> VertexOutput {
    // The unit quad covers the layer's **region** (milestone 610): the whole target for a
    // layer that may draw anywhere, only its clip for one that may not. Outside the region
    // there is nothing of the layer, so nothing to shade. `uv` stays the target's, which is
    // what the full-target clip mask is read in.
    let px = inst.region.xy + vert.unit_pos * inst.region.zw;
    let unit = px / viewport.size;
    let ndc = vec2<f32>(unit.x * 2.0 - 1.0, 1.0 - unit.y * 2.0);
    var out: VertexOutput;
    out.clip_position = vec4<f32>(ndc, 0.0, 1.0);
    out.uv = unit;
    out.frag_px = px;
    out.region = inst.region;
    out.clip = inst.clip;
    out.opacity = inst.inv_tr_op.z;
    out.inv_lin = inst.inv_lin;
    out.inv_tr = inst.inv_tr_op.xy;
    out.shape = inst.shape;
    out.radii = inst.radii;
    return out;
}

// Signed distance to a rounded rectangle centred at the origin, of half-size
// `half` and radius `r`: negative inside, positive outside. The basis of rounded
// corners.
fn sd_rounded_box(p: vec2<f32>, half: vec2<f32>, r: f32) -> f32 {
    let q = abs(p) - half + vec2<f32>(r, r);
    return length(max(q, vec2<f32>(0.0, 0.0))) + min(max(q.x, q.y), 0.0) - r;
}

// The corner radius matching `p`'s quadrant (centred, y pointing down).
// radii = (tl, tr, br, bl).
fn corner_radius(p: vec2<f32>, radii: vec4<f32>) -> f32 {
    if (p.x < 0.0) {
        return select(radii.w, radii.x, p.y < 0.0); // left: top → tl, bottom → bl
    }
    return select(radii.z, radii.y, p.y < 0.0);     // right: top → tr, bottom → br
}

// linear -> sRGB. The inverse of what the sampler already did for us; needed
// because the filters below are defined on the encoded values, not on light.
fn linear_to_srgb(c: vec3<f32>) -> vec3<f32> {
    let lower = c * 12.92;
    let higher = 1.055 * pow(max(c, vec3<f32>(0.0)), vec3<f32>(1.0 / 2.4)) - 0.055;
    return select(higher, lower, c <= vec3<f32>(0.0031308));
}

fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {
    let lower = c / 12.92;
    let higher = pow((c + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4));
    return select(higher, lower, c <= vec3<f32>(0.04045));
}

// The ends of a channel, give or take far less than one 8-bit step: a value read back
// from an sRGB target is decoded and encoded again, and 1.0 comes back as 0.99999. The
// dodge and the burn turn on those ends exactly (milestone 646).
const EDGE: f32 = 1e-4;

// One channel of a separable blend, on **straight** values.
fn separable(sc: f32, dc: f32, mode: u32) -> f32 {
    if (mode == 13u) {                      // Multiply
        return sc * dc;
    } else if (mode == 14u) {               // Screen
        return sc + dc - sc * dc;
    } else if (mode == 15u) {               // Overlay: Hard-light with the roles swapped
        if (dc <= 0.5) {
            return 2.0 * sc * dc;
        }
        return 1.0 - 2.0 * (1.0 - sc) * (1.0 - dc);
    } else if (mode == 16u) {               // Darken
        return min(sc, dc);
    } else if (mode == 17u) {               // Lighten
        return max(sc, dc);
    } else if (mode == 19u) {               // ColorDodge
        if (dc <= EDGE) {
            return 0.0;
        }
        if (sc >= 1.0 - EDGE) {
            return 1.0;
        }
        return min(1.0, dc / (1.0 - sc));
    } else if (mode == 20u) {               // ColorBurn
        if (dc >= 1.0 - EDGE) {
            return 1.0;
        }
        if (sc <= EDGE) {
            return 0.0;
        }
        return 1.0 - min(1.0, (1.0 - dc) / sc);
    } else if (mode == 21u) {               // HardLight: Overlay with the roles swapped
        if (sc <= 0.5) {
            return 2.0 * sc * dc;
        }
        return 1.0 - 2.0 * (1.0 - sc) * (1.0 - dc);
    } else if (mode == 22u) {               // SoftLight
        if (sc <= 0.5) {
            return dc - (1.0 - 2.0 * sc) * dc * (1.0 - dc);
        }
        var d = sqrt(dc);
        if (dc <= 0.25) {
            d = ((16.0 * dc - 12.0) * dc + 4.0) * dc;
        }
        return dc + (2.0 * sc - 1.0) * (d - dc);
    } else if (mode == 23u) {               // Difference
        return abs(sc - dc);
    }
    return sc + dc - 2.0 * sc * dc;         // 24 Exclusion
}

// The non-separable modes' helpers: luminosity, saturation, and setting each while
// keeping the colour in gamut.
fn lum(c: vec3<f32>) -> f32 {
    return dot(c, vec3<f32>(0.3, 0.59, 0.11));
}

fn clip_color(c: vec3<f32>) -> vec3<f32> {
    let l = lum(c);
    let n = min(min(c.r, c.g), c.b);
    let x = max(max(c.r, c.g), c.b);
    var o = c;
    if (n < 0.0) {
        o = vec3<f32>(l) + (o - vec3<f32>(l)) * l / max(l - n, 1e-6);
    }
    if (x > 1.0) {
        o = vec3<f32>(l) + (o - vec3<f32>(l)) * (1.0 - l) / max(x - l, 1e-6);
    }
    return o;
}

fn set_lum(c: vec3<f32>, l: f32) -> vec3<f32> {
    return clip_color(c + vec3<f32>(l - lum(c)));
}

fn sat(c: vec3<f32>) -> f32 {
    return max(max(c.r, c.g), c.b) - min(min(c.r, c.g), c.b);
}

fn set_sat(c: vec3<f32>, s: f32) -> vec3<f32> {
    let lo = min(min(c.r, c.g), c.b);
    let hi = max(max(c.r, c.g), c.b);
    if (hi > lo) {
        return (c - vec3<f32>(lo)) * s / (hi - lo);
    }
    return vec3<f32>(0.0);
}

// One of the four non-separable modes, on **straight** colours.
fn non_separable(sc: vec3<f32>, dc: vec3<f32>, mode: u32) -> vec3<f32> {
    if (mode == 25u) {                      // Hue
        return set_lum(set_sat(sc, sat(dc)), lum(dc));
    } else if (mode == 26u) {               // Saturation
        return set_lum(set_sat(dc, sat(sc)), lum(dc));
    } else if (mode == 27u) {               // Color
        return set_lum(sc, lum(dc));
    }
    return set_lum(dc, lum(sc));            // 28 Luminosity
}

// `src` over `dst` under `mode`, both **premultiplied**. The Porter-Duff modes are
// linear in the premultiplied values, which is why they are one line each; the
// separable modes are not, so they are unpremultiplied first and the standard
// composition is spelled out.
fn blend(src: vec4<f32>, dst: vec4<f32>, mode: u32) -> vec4<f32> {
    let sa = src.a;
    let da = dst.a;
    if (mode == 0u) { return src; }                                  // Src
    if (mode == 1u) { return dst; }                                  // Dst
    if (mode == 2u) { return src + dst * (1.0 - sa); }               // SrcOver
    if (mode == 3u) { return dst + src * (1.0 - da); }               // DstOver
    if (mode == 4u) { return src * da; }                             // SrcIn
    if (mode == 5u) { return dst * sa; }                             // DstIn
    if (mode == 6u) { return src * (1.0 - da); }                     // SrcOut
    if (mode == 7u) { return dst * (1.0 - sa); }                     // DstOut
    if (mode == 8u) { return src * da + dst * (1.0 - sa); }          // SrcAtop
    if (mode == 9u) { return dst * sa + src * (1.0 - da); }          // DstAtop
    if (mode == 10u) {                                               // Xor
        return src * (1.0 - da) + dst * (1.0 - sa);
    }
    if (mode == 11u) {                                               // Plus
        return min(src + dst, vec4<f32>(1.0));
    }
    if (mode == 12u) {                                               // Modulate
        return src * dst;
    }
    if (mode == 18u) {                                               // Clear
        return vec4<f32>(0.0);
    }
    // The separable set and the four that are not: unpremultiply, blend, recompose.
    let sc = select(src.rgb / sa, vec3<f32>(0.0), sa <= 0.0);
    let dc = select(dst.rgb / da, vec3<f32>(0.0), da <= 0.0);
    var b: vec3<f32>;
    if (mode >= 25u) {
        b = non_separable(sc, dc, mode);
    } else {
        b = vec3<f32>(
            separable(sc.r, dc.r, mode),
            separable(sc.g, dc.g, mode),
            separable(sc.b, dc.b, mode),
        );
    }
    let rgb = (1.0 - da) * src.rgb + (1.0 - sa) * dst.rgb + sa * da * b;
    return vec4<f32>(rgb, sa + da - sa * da);
}

// The mask's colour at a screen pixel: a two-stop fade, straight and sRGB-encoded
// like the colours it was authored from.
fn mask_color(p: vec2<f32>, kind: f32) -> vec4<f32> {
    var t: f32;
    if (kind < 1.5) {
        // Linear: the projection of `p` onto the from-to segment, clamped.
        let start = fx.mask_geom.xy;
        let axis = fx.mask_geom.zw - start;
        let len2 = dot(axis, axis);
        t = select(dot(p - start, axis) / len2, 0.0, len2 <= 0.0);
    } else {
        // Radial: the distance from the centre, over the radius.
        let center = fx.mask_geom.xy;
        let radius = fx.mask_geom.z;
        t = select(length(p - center) / radius, 1.0, radius <= 0.0);
    }
    return mix(fx.mask_c0, fx.mask_c1, clamp(t, 0.0, 1.0));
}

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    // The layer transform: the texture holds the content **flat** — untransformed —
    // at its screen position. To paint the layer transformed by M we sample at the
    // **counter-transformed** position M⁻¹(p), so screen pixel p receives the content
    // that, transformed by M, lands on p. With `inv_lin = ia,ib,ic,id` and
    // `inv_tr = ie,if`: src = (ia·x + ic·y + ie, ib·x + id·y + if).
    let p = in.frag_px;
    let src_px = vec2<f32>(
        in.inv_lin.x * p.x + in.inv_lin.z * p.y + in.inv_tr.x,
        in.inv_lin.y * p.x + in.inv_lin.w * p.y + in.inv_tr.y,
    );
    // The texture holds the region, from its corner.
    let src_uv = (src_px - in.region.xy) / in.region.zw;

    // Outside the texture after counter-rotation: nothing, a transparent edge.
    let in_bounds = f32(
        src_uv.x >= 0.0 && src_uv.x <= 1.0 && src_uv.y >= 0.0 && src_uv.y <= 1.0
    );
    // Clip coverage, tested on the screen pixel and **inscribed** in `clip`: a hard
    // rectangle (kind 0), rounded corners (kind 1) or an ellipse (kind 2). The curved
    // shapes are antialiased over roughly 1 px through the signed distance.
    let center = in.clip.xy + in.clip.zw * 0.5;
    let half = in.clip.zw * 0.5;
    let q = in.frag_px - center;
    let kind = in.shape.x;
    // The rectangular test, shared by a bare rect and a path's **bounds**.
    let in_rect = f32(
        in.frag_px.x >= in.clip.x
        && in.frag_px.x <= in.clip.x + in.clip.z
        && in.frag_px.y >= in.clip.y
        && in.frag_px.y <= in.clip.y + in.clip.w
    );
    var clip_cov: f32;
    if (kind < 0.5) {
        clip_cov = in_rect; // a hard rectangle, the original behaviour
    } else if (kind < 1.5) {
        // Rounded corners, **per corner**: the quadrant's radius, capped at half the
        // smaller dimension.
        let r = min(corner_radius(q, in.radii), min(half.x, half.y));
        let d = sd_rounded_box(q, half, r);
        clip_cov = 1.0 - smoothstep(-0.5, 0.5, d);
    } else if (kind < 2.5) {
        // The inscribed ellipse: an approximate, gradient-normalised edge distance.
        let e = q / max(half, vec2<f32>(1.0, 1.0));
        let g = length(e);
        let d = (g - 1.0) * min(half.x, half.y);
        clip_cov = 1.0 - smoothstep(-0.5, 0.5, d);
    } else {
        clip_cov = in_rect; // a path: rectangular bounds; the shape comes from the mask
    }
    // The coverage mask: solid white outside ClipPath → a neutral multiplication.
    let mask_a = textureSample(mask, samp, in.uv).a;
    let inside_clip = clip_cov * mask_a;
    let sample = textureSample(tex, samp, src_uv);
    // What is under the layer, read here, ahead of any branch: a blend needs it.
    let under = textureSample(under_tex, samp, in.uv);
    // The group opacity and every coverage term, as one factor.
    let cover = in.opacity * inside_clip * in_bounds;
    let color_kind = fx.flags.x;
    let mask_kind = fx.flags.y;
    let blending = fx.blend.x > 0.5;
    if (!blending && color_kind < 0.5 && mask_kind < 0.5) {
        // The overwhelmingly common case: no filter at all.
        //
        // The layer texture is **premultiplied** — it was painted over a transparent
        // target, which is what the (SrcAlpha, 1-SrcAlpha) blend leaves behind — so
        // scaling both halves by the coverage and letting the target blend with
        // (One, 1-SrcAlpha) is the correct "over", with no double-blending inside the
        // layer and none at its edge either.
        return vec4<f32>(sample.rgb * cover, sample.a * cover);
    }

    // The layer texture holds premultiplied linear light. The filters are defined on
    // straight, sRGB-encoded values, so we go there and come back.
    let a = sample.a;
    let straight = select(sample.rgb / a, vec3<f32>(0.0), a <= 0.0);
    var c = vec4<f32>(linear_to_srgb(straight), a);

    if (color_kind > 0.5 && color_kind < 1.5) {
        // The 5x4 matrix, on (r, g, b, a, 1).
        let v = c;
        c = vec4<f32>(
            dot(fx.m0, v) + fx.m4.x,
            dot(fx.m1, v) + fx.m4.y,
            dot(fx.m2, v) + fx.m4.z,
            dot(fx.m3, v) + fx.m4.w,
        );
        c = clamp(c, vec4<f32>(0.0), vec4<f32>(1.0));
    } else if (color_kind > 1.5) {
        // A colour blended into every pixel.
        let src = vec4<f32>(fx.mode_color.rgb * fx.mode_color.a, fx.mode_color.a);
        let dst = vec4<f32>(c.rgb * c.a, c.a);
        let out = blend(src, dst, u32(fx.flags.z));
        c = vec4<f32>(select(out.rgb / out.a, vec3<f32>(0.0), out.a <= 0.0), out.a);
    }

    if (mask_kind > 0.5) {
        let m = mask_color(in.frag_px, mask_kind);
        let src = vec4<f32>(m.rgb * m.a, m.a);
        let dst = vec4<f32>(c.rgb * c.a, c.a);
        let out = blend(src, dst, u32(fx.flags.w));
        c = vec4<f32>(select(out.rgb / out.a, vec3<f32>(0.0), out.a <= 0.0), out.a);
    }

    if (blending) {
        // The layer meets what is under it by its mode (milestone 646), both
        // premultiplied and sRGB-encoded, as colours are written. The opacity belongs
        // to the layer's colour; the clip's edge is coverage, so what the clip leaves
        // out keeps what was there. This draw replaces the target, so the result is the
        // whole of the pixel.
        let s = vec4<f32>(c.rgb * c.a, c.a) * in.opacity;
        let ua = under.a;
        let us = select(under.rgb / ua, vec3<f32>(0.0), ua <= 0.0);
        let d = vec4<f32>(linear_to_srgb(us) * ua, ua);
        let r = blend(s, d, u32(round(fx.blend.x)) - 1u);
        let o = mix(d, r, inside_clip * in_bounds);
        let os = select(o.rgb / o.a, vec3<f32>(0.0), o.a <= 0.0);
        let ol = srgb_to_linear(clamp(os, vec3<f32>(0.0), vec3<f32>(1.0)));
        return vec4<f32>(ol * o.a, o.a);
    }

    // Back to premultiplied linear, in the same convention as the fast path above.
    let lin = srgb_to_linear(clamp(c.rgb, vec3<f32>(0.0), vec3<f32>(1.0)));
    return vec4<f32>(lin * c.a * cover, c.a * cover);
}