Krolyxon
Commit 9f6e071

Branches

Tags

Refs →

remagesrcrendershadersprims.wgsl

60 lines · 1.9 KB · WGSL

1// Instanced SDF primitives: rects, rounded rects, borders and dots. Output is premultiplied.
2
3struct Globals {
4 viewport: vec2<f32>,
5 _pad: vec2<f32>,
6};
7
8@group(0) @binding(0) var<uniform> g: Globals;
9
10struct Instance {
11 @location(0) rect: vec4<f32>, // x, y, w, h in physical px
12 @location(1) color: vec4<f32>, // linear, straight alpha
13 @location(2) border_color: vec4<f32>,
14 @location(3) params: vec4<f32>, // x: corner radius, y: border width
15};
16
17struct VOut {
18 @builtin(position) pos: vec4<f32>,
19 @location(0) local: vec2<f32>,
20 @location(1) half: vec2<f32>,
21 @location(2) color: vec4<f32>,
22 @location(3) border_color: vec4<f32>,
23 @location(4) params: vec4<f32>,
24};
25
26@vertex
27fn vs(@builtin(vertex_index) i: u32, inst: Instance) -> VOut {
28 var corners = array<vec2<f32>, 6>(
29 vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(-1.0, 1.0),
30 vec2(-1.0, 1.0), vec2(1.0, -1.0), vec2(1.0, 1.0),
31 );
32 let half = inst.rect.zw * 0.5;
33 // Pad by a pixel so the anti-aliased edge isn't clipped.
34 let local = corners[i] * (half + 1.0);
35 let p = inst.rect.xy + half + local;
36 var out: VOut;
37 out.pos = vec4(p.x / g.viewport.x * 2.0 - 1.0, 1.0 - p.y / g.viewport.y * 2.0, 0.0, 1.0);
38 out.local = local;
39 out.half = half;
40 out.color = inst.color;
41 out.border_color = inst.border_color;
42 out.params = inst.params;
43 return out;
44}
45
46@fragment
47fn fs(in: VOut) -> @location(0) vec4<f32> {
48 let r = min(in.params.x, min(in.half.x, in.half.y));
49 let q = abs(in.local) - in.half + r;
50 let d = length(max(q, vec2(0.0))) + min(max(q.x, q.y), 0.0) - r;
51 let coverage = clamp(0.5 - d, 0.0, 1.0);
52 let fill = vec4(in.color.rgb * in.color.a, in.color.a);
53 var c = fill;
54 let bw = in.params.y;
55 if bw > 0.0 {
56 let border = vec4(in.border_color.rgb * in.border_color.a, in.border_color.a);
57 c = mix(border, fill, clamp(0.5 - (d + bw), 0.0, 1.0));
58 }
59 return c * coverage;
60}