Skip to content

Instantly share code, notes, and snippets.

@pineapplemachine
Created November 6, 2021 23:01
Show Gist options
  • Select an option

  • Save pineapplemachine/cab50932b3ee9e6127fb4d6cda9e2e8f to your computer and use it in GitHub Desktop.

Select an option

Save pineapplemachine/cab50932b3ee9e6127fb4d6cda9e2e8f to your computer and use it in GitHub Desktop.
MSDF fragment shader scratch
// This code is distributed under the Unlicense https://unlicense.org/
// In other words, I am releasing it as public domain.
// Reasonably well working MSDF fragment shader.
// Good discussion per shader: https://github.com/Chlumsky/msdfgen/issues/22
export const TextGlyphFragmentShader = `
precision mediump float;
// Contains MSDF glyph data
uniform sampler2D u_glyphTexture;
// Weight to render the font with. Weight 1 = normal.
uniform float u_fontWeight;
// Smoothing to render with. Smoothing 1 = normal.
uniform float u_fontSmoothing;
// Proportional to the distance range that the MSDF was created with.
uniform float u_distanceRange;
// UV coords received from the vertex shader
varying vec2 v_position;
float median(vec3 v) {
return max(min(v.x, v.y), min(max(v.x, v.y), v.z));
}
#define FRACTION_1_64 0.015625
// TODO: look at other better frag shader options
void main(){
vec3 sample = texture2D(u_glyphTexture, v_position).rgb;
float dist = u_distanceRange * (median(sample) - 0.5) + (u_fontWeight - 1.0);
float weight = min(1.0, 0.325 * u_distanceRange) * u_fontSmoothing;
float t = smoothstep(-weight, +weight, dist);
if(t >= FRACTION_1_64) gl_FragColor = vec4(t, t, t, 1.0);
else discard;
}
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment