Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / library / map / src / main / rust / shaders / symbol.frag

symbol.frag46 lines · 2.1 KiBRaw
1#version 450
2
3// Symbol fragment: SDF text with halo.
4//
5// The atlas texel is signed distance, 0.0 far outside to 1.0 deep inside, with
6// the glyph edge at 0.5. `smoothstep` across a 1-texel band gives crisp edges at
7// any size; the halo is the same edge test on a dilated threshold, drawn first
8// in the halo color so the face overpaints it.
9
10layout(location = 0) in vec2 inUv;
11
12layout(location = 0) out vec4 outColor;
13
14layout(push_constant) uniform Push {
15 mat4 tileToClip;
16 vec4 color;
17 // x: text size in device px per em, y: halo width in device px, z: SDF value
18 // change across one em, w: unused.
19 vec4 line;
20 // x: tile span in px, yzw: halo color rgb.
21 vec4 misc;
22} push;
23layout(set = 0, binding = 0) uniform sampler2D atlas;
24void main() {
25 // SDF is in `.r` by the upload contract (`glyph::expand_sdf_r8_to_rgba8`
26 // writes [v, v, v, v]; pinned by
27 // `the_rgba8_expansion_carries_sdf_in_every_channel`).
28 float dist = texture(atlas, inUv).r;
29 // Smooth across exactly one screen pixel of the distance field. `fwidth` is how
30 // much `dist` changes between neighbouring fragments, so this tracks the label's
31 // size for free. The previous constant band was one atlas texel of the 0..1 SDF
32 // range - about 0.001 - which is far narrower than a pixel at any label size and
33 // so drew hard, aliased edges.
34 float aa = max(fwidth(dist), 1e-4);
35 float face = smoothstep(0.5 - aa, 0.5 + aa, dist);
36 // Halo: the edge test dilated outwards. A halo of `haloPx` screen px is
37 // `haloPx / textPx` ems, and `line.z` is how much the SDF moves across an em.
38 float haloSdf = push.line.y / max(push.line.x, 1.0) * push.line.z;
39 float halo = smoothstep(0.5 - haloSdf - aa, 0.5 - haloSdf + aa, dist);
40 vec3 haloRgb = push.misc.yzw;
41 // Without a halo the face's own antialiased edge must not pick up the halo colour.
42 vec3 rgb = haloSdf > 0.0 ? mix(haloRgb, push.color.rgb, face) : push.color.rgb;
43 float alpha = max(halo * push.color.a, face * push.color.a);
44 if (alpha <= 0.001) discard;
45 outColor = vec4(rgb, alpha);
46}