如何根据时间或某些功能动态更改每个Vertex的颜色?

时间:2017-12-28 05:23:50

标签: c++ opengl

我想绘制高斯函数的二维轮廓(Z = f(x,y,sigma))。 x,y是Vertex的x,y; z = 0。我使用Z得到每个顶点的颜色。当sigma改变为0.01-1.0时,Z和颜色值将改变。如何更新颜色?

  glBufferData(GL_ARRAY_BUFFER, sizeof(GaussianVertexices), GaussianVertexices,    GL_STATIC_DRAW);//GaussianVertexices contains Pos and Color;
//...
while (!glfwWindowShouldClose(window))
{
    glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    GaussShader.use();
    sigma += 0.01;
    if (sigma>1.0)
    {
        sigma = 0.1;
    }
    // how can i update color value with sigma changed
    glBindVertexArray(GaussVAO);
    glPointSize(2.0f);
    glDrawArrays(GL_POINTS, 0, POINTS_NUMS);
    glfwSwapBuffers(window);
    glfwPollEvents();
}

顶点着色器:

#version 330 core
layout(location=0) in vec2 apos;
layout(location=1) in vec3 acolor;

out vec3 color;


void main()
{
    gl_Position=vec4(apos.x,apos.y,0.0,1.0f);
    color=acolor;
}

片段着色器

#version 330 core
in vec3 color;
out vec4 fragColor;

void main()
{
    fragColor=vec4(color,0.5);
}

更新: 我试过这个。

 while (!glfwWindowShouldClose(window))
    {//....
        GaussShader.use();
        sigma += 0.01;
        CreateGuassColor(GaussVertexices, GaussColor);
        if (sigma>1.0)
        {
            sigma = 0.01;
        }

        glBindVertexArray(GaussVAO);
        glBindBuffer(GL_ARRAY_BUFFER, ColorVBO);
        void *ptr = nullptr;
          ptr  = glMapBufferRange(GL_ARRAY_BUFFER, 0, sizeof(GaussColor), GL_MAP_WRITE_BIT);

        memcpy(ptr, GaussColor, sizeof(GaussColor));
        glUnmapBuffer(GL_ARRAY_BUFFER);
        glBindVertexArray(0);
        glBindVertexArray(GaussVAO);
        glPointSize(2.0f);
        glDrawArrays(GL_POINTS, 0, POINTS_NUMS);
    }

1 个答案:

答案 0 :(得分:1)

添加:

uniform vec4 vertexColor;

到你的片段着色器。

确保在首次创建着色器程序时获取着色器程序的ID。这是在您编译和链接顶点和片段着色器之前。你这样做:

GLuint gaussShaderProg = glCreateProgram(); 

然后做:

GLint uniformLocation = glGetUniformLocation(gaussShaderProg, "vertexColor");

然后在你的循环中:

while (!glfwWindowShouldClose(window))
{
    glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

    sigma += 0.01;
    if (sigma>1.0)
    {
        sigma = 0.1;
    }

    GaussShader.use(); // Make sure the shader program is 
                       // bound before trying to     update the uniform

    float vertColor[] = { 1, 1, 1, 1 }; // Whatever colour you want
    glUniform4fv(uniformLocation​, 1, (GLfloat*)vertColor​); // Now your fragment shader 
                                         // can access the updated colour


    glBindVertexArray(GaussVAO);
    glPointSize(2.0f);
    glDrawArrays(GL_POINTS, 0, POINTS_NUMS);
    glfwSwapBuffers(window);
    glfwPollEvents();
}

然后在片段着色器中输出均匀的颜色(vec4)。确保颜色的第四个分量是1,以防你进行alpha混合。