Circle, Disc and Fake Sphere in GLSL (Shader Library)

Article index:

3 – A Disc in GLSL

GLSL Hacker - GLSL program to draw a disc

Here is the GLSL program to draw a disc. The edge of the disc is blurred with the help of the smoothstep function.

Vertex shader:

#version 120    
void main()
  gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;		
  gl_TexCoord[0] = gl_MultiTexCoord0;

Fragment shader:

#version 120    
uniform sampler2D tex0;
uniform float border_size; // 0.01
uniform float disc_radius; // 0.5
uniform vec4 disc_color; // vec4(1.0, 1.0, 1.0, 1.0)
uniform vec2 disc_center; // vec2(0.5, 0.5)    
void main (void)
  vec2 uv = gl_TexCoord[0].xy;
  vec4 bkg_color = texture2D(tex0,uv * vec2(1.0, -1.0));

  // Offset uv with the center of the circle.
  uv -= disc_center;

  float dist = sqrt(dot(uv, uv));
  float t = smoothstep(disc_radius+border_size, disc_radius-border_size, dist);
  gl_FragColor = mix(bkg_color, disc_color, t);

Article index:


  • Nathan

    You can anti-alias the fake sphere’s edges by modifying the alpha channel with a smoothstep function. The one used in the Disc demo should do the trick, just adjust the values so it won’t be so thick.

  • Thanks Nathan. I quickly ported the fake sphere demo without thinking to the antialiasing and as you said, the smoothstep function can help to antialiase.