Shader allows me to implement new effects freely. This example shows that the shader program is used to process vertices in a strange way.
First, we set the zcoordinate to 0 before the Model View transformation to flatten the 3D model. Vertex shader:
void main(void){vec4 v = vec4(gl_Vertex);v.z = 0.0;gl_Position = gl_ModelViewProjectionMatrix * v;}
First, assign gl_vertex to a local variable. gl_vertex is an attribute variable provided by glsl. Therefore, it is read-only in the vertex shader, therefore, you need to assign a local variable V to modify the vertex value entered by the application.
The shader is only used to set the color, so it can be the same as in the helloworld mentioned above.
Here, we set the Z value to 0 in the vertex program and apply it to a teapot model. The result may be as follows:
Then let me try other results and calculate the Z calculation items as follows. The results may be as follows:
void main(void){vec4 v = vec4(gl_Vertex);v.z = sin(5.0*v.x )*0.25;gl_Position = gl_ModelViewProjectionMatrix * v;}
Now, we are going to add some vertex animations. First, we need a variable to track the current time. The vertex program cannot do this. Therefore, we need to define this variable in the OpenGL application, and pass the uniform variable to the vertex shader. Suppose there is a time variable in the application, and there is an uniform variable with the same name in the vertex shader, then the vertex shader becomes like this:
uniform float time;void main(void){vec4 v = vec4(gl_Vertex);v.z = sin(5.0*v.x + time*0.01)*0.25;gl_Position = gl_ModelViewProjectionMatrix * v;}
As mentioned above, the Application Section has two steps:
Set up: get the location of the attribute variable
Rendering: Update attribute variables
Build phase: Loc = glgetuniformlocationarb (P, "Time ");
Here, p is the handle of the vertex shader, time is the uniform variable, and loc is the glint type. You should define the locations that can be accessed in a certain rendering stage.
The rendering function may look like this:
void renderScene(void) {glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);glLoadIdentity();gluLookAt(0.0,0.0,5.0, 0.0,0.0,0.0,0.0f,1.0f,0.0f);glUniform1fARB(loc, time);glutSolidTeapot(1);time+=0.01;glutSwapBuffers();}
Here, the initial value given by the time variable during initialization is updated at each frame.
The project code can be downloaded here.