Reputation: 641
I'm a beginner, I try to draw a circle by drawing a square. But failed! Here's my vertex shader:
#define RADIUS 0.5
#define WHITE vec4(1.0,1.0,1.0,1.0)
#define RED vec4(1.0,0.0,0.0,1.0)
attribute vec2 a_position;
varying vec4 v_color; //defines color in fragment shader
....
void main(){
gl_Position = a_position;
v_color = (a_position[0]*a_position[0]+a_position[1]*position[1]<RADIUS*RADIUS) ? RED : WHITE;
}
It does not work as I want. WHY?
Upvotes: 1
Views: 2030
Reputation: 54562
In short: Not like this!
As the name suggests, the code in a vertex shader is executed once per vertex. So if you draw a square, the vertex shader is only executed for the 4 vertices you specify for the draw call.
The expression you have in your shader code needs to be executed for each fragment (at least for this discussion, you can assume that fragment is the same as a pixel). You want to evaluate for each pixel if it is inside or outside the circle. Therefore, the logic needs to be in the fragment shader.
To get this working, it's easiest if you pass the original position to the fragment shader. There is a built-in variable (gl_FragCoord) for the position available in the fragment shader, but it is in pixels, which makes your calculation more complicated.
So your vertex shader would look like this:
attribute vec2 a_position;
varying vec2 v_origPosition;
...
void main() {
gl_Position = a_position;
v_origPosition = a_position;
}
Most of what you had in the vertex shader then goes to the fragment shader:
...
varying vec2 v_origPosition;
...
void main() {
gl_FragColor = (dot(v_origPosition, v_origPosition) < RADIUS * RADIUS) ? ...
Upvotes: 2