1.在vertex shader中新增一个输出变量
代码语言:javascript复制const char* vertexShaderSource =
"#version 330 core n"
"layout (location = 0) in vec3 aPos; n"
"out vec4 vertexColor; n"
"void main() n"
"{ n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);n"
" vertexColor = vec4(1.0,1.0,0,1.0); n"
"} n";
const char* fragmentShaderSource =
"#version 330 core n"
"in vec4 vertexColor; n"
"out vec4 FragColor; n"
"void main(){ n"
" FragColor =vertexColor;} n";
Uniform是一种从CPU的应用向GPU中的着色器发送数据的方式,uniform是全局的,uniform可以被着色器的任意阶段访问。 2.通过Uniform实现颜色渐变
代码语言:javascript复制const char* fragmentShaderSource =
"#version 330 core n"
"in vec4 vertexColor; n"
"uniform vec4 ourColor; n"
"out vec4 FragColor; n"
"void main(){ n"
" FragColor =ourColor;} n";
代码语言:javascript复制 float timeValue = glfwGetTime();
float greenValue = (sin(timeValue) / 2.0f) 0.5f;
int vertexColorLocation = glGetUniformLocation(shaderProgram, "ourColor");
//glBindVertexArray(VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glUseProgram(shaderProgram);
glUniform4f(vertexColorLocation, 0, greenValue, 0, 1.0f);
//glDrawArrays(GL_TRIANGLES, 0, 6);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);