Color Shader
GLSL has access to part of the OpenGL state. In this tutorial we'll see how to access the color as set in an OpenGL application with glColor.
GLSL has an attribute variable where it keeps track of the current color. It also provides varying variables to get the color from the vertex shader to the fragment shader //顶点着色器的属性变量用来访问固定管线的状态,如当前艳色,当前顶点坐标等,同时varying(传递变量)变量用来把变量值从顶点着色器传给片元着色器
attribute vec4 gl_Color;//属性变量,得到当前艳色即glColro()设置的艳色 varying vec4 gl_FrontColor; // writable on the vertex shader//可写的前景色,即可以传固定管线或者片元着色器使用 varying vec4 gl_BackColor; // writable on the vertex shader varying vec4 gl_Color; // readable on the fragment shader//The idea is as follows:
- The OpenGL applications sends a color using the glColor function //openGL用glColor()设置艳色
- The vertex shader receives the color value in the attribute gl_Color //顶点着色器用gl_Color得到glColor()设置的艳色
- The vertex shader computes the front face and back face colors, and stores them in gl_FrontColor, and gl_BackColor respectively //顶点着色器计算前面的艳色和背面的艳色,并存入gl_FrontColor和gl_BackColor
- The fragment shader receives an interpolated color in the varying variable gl_Color, depending on the orientation of the current primitive, i.e. the interpolation is done using either the gl_FrontColor or the gl_BackColor values. //片元着色器接收到通过gl_Color插值而计算得到的艳色,根据图元的顶点设置的顺序来决定用gl_FrontColor或者gl_BackColor,具体使用哪一个变量根据glFrontMode()确定
- The fragment shader sets gl_FragColor based on the value of gl_Color
Enough talk, the code for the vertex shader, where only the front face color is computed is:
void main() { gl_FrontColor = gl_Color;//gl_Color是当前顶点艳色 gl_Position = ftransform(); }
The fragment shader is also a very simple shader:
void main() { gl_FragColor = gl_Color;//gl_Color是经过插值后每个片元的艳色 } //------------补充
在这里有两个gl_Color,意义是不同的,分别用于顶点着色器和片元着色器中,在顶点着色器中,gl_Color的艳色来自于函数glColor()
设置的当前艳色,而gl_FrontColor还是gl_BackColor接收gl_Color的艳色,则由函数glFrontMode()的参数决定
在片元着色器中,gl_Color的值从固定管线得到,是经过顶点艳色插值后的得到的艳色