Wednesday, November 7, 2012

OpenGL - GLSL - Draw a circle with a geometry shader

This is a quick and dirty way to draw a circle facing the screen by using the geometry shader. From what I've read around the net, using the geometry shader to produce a large number of primitives is not a good idea and slows down things a lot so please use the following code with caution. I assume you know how to compile and link shaders as well as what VBO's and VAO's are.


/* [GEOMETRY] */
#version 330

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;


layout(points) in;
layout(line_strip, max_vertices = 200)out;

void main()
{
//float PI = 3.14159265358979323846264;  //unused

    vec4 pos = vec4(0,0,0,1);  //introduce a single vertex at the origin
    pos = projection*view*model*pos;  //translate it to where our model is
                                                            //ideally do this step outside the shader

    for(float i = 0; i < 6.38 ; i+=0.1)  //generate vertices at positions on the circumference from 0 to 2*pi
{
        gl_Position = vec4(pos.x+0.5*cos(i),pos.y+0.5*sin(i),pos.z,1.0);   //circle parametric equation
EmitVertex();      
      }
}

The vertex shader does nothing and the fragment shader simply outputs a color passed in by a uniform.

No comments:

Post a Comment