使用2个着色器渲染两个重叠的2D对象

时间:2016-10-20 16:13:58

标签: c++ opengl

我想渲染两个蓝色的三角形和一个#34;风车"红色的。为此,我创建了2个着色器,除了颜色外,它们是相同的。这两个三角形比#34; windmill"大得多。我面临的问题是,如果我在着色器之间切换,那么只会渲染最后一个对象。如果我切换到仅使用1个着色器,则会绘制两个对象,但我几乎看不到"风车"因为颜色一样。所以我的问题是如何使用两个着色器绘制两个对象? (我知道我可以将颜色传递给片段着色器,但我不想这样做。)

渲染循环:

GLint index, index2;
index = glGetUniformLocation(shaders[LINE], "projectionMatrix");
index2 = glGetUniformLocation(shaders[TRIANGLE], "projectionMatrix");
glUniformMatrix3fv(index, 1, true, value_ptr(projectionMatrix));
glUniformMatrix3fv(index2, 1, true, value_ptr(projectionMatrix));
glClear(GL_COLOR_BUFFER_BIT);

glUseProgram(shaders[TRIANGLE]);
glBindVertexArray(vaos[TRIANGLE]);
glDrawArrays(GL_TRIANGLES, 0, tbufindex/sizeof(glm::vec3));

glUseProgram(shaders[LINE]); // If I comment out this line both objects will be drawn
glBindVertexArray(vaos[LINE]);
glDrawArrays(GL_LINE_STRIP, 0, sizeof(vertices_position)/sizeof(glm::vec3));

线/ Triangle.vert:

#version 450
layout (location = 0) in vec3 vPosition;
uniform mat3 projectionMatrix;

void main()
{
    vec3 tmp = projectionMatrix*vPosition;
    gl_Position = vec4(tmp, 1.0f);
}

线/ triangle.frag:

#version 450
in vec4 gl_FragCoord;
out vec4 fColor;

void main()
{
    fColor = vec4(0.0, 0.0, 1.0, 1.0);
}

另请注意,我没有启用GL_DEPTH_TEST,我使用的是2D坐标。

编辑职位:

triangles[2] = { { vec3(-0.90f, -0.90f, 1.0f), vec3(0.85f, -0.90f, 1.0f), vec3(-0.90f, 0.85f, 1.0f) },
{ vec3(0.90f, -0.85f, 1.0f),  vec3(0.90f, 0.90f, 1.0f),  vec3(-0.85f, 0.90f, 1.0f) } };

lines[39] = {
    0.0f, 0.0f, 1.0f,
    0.5f, 0.0f, 1.0f,
    0.5f, 0.5f, 1.0f,
    0.0f, 0.0f, 1.0f,
    0.0f, 0.5f, 1.0f,
    -0.5f, 0.5f, 1.0f,
    0.0f, 0.0f, 1.0f,
    -0.5f, 0.0f, 1.0f,
    -0.5f, -0.5f, 1.0f,
    0.0f, 0.0f, 1.0f,
    0.0f, -0.5f, 1.0f,
    0.5f, -0.5f, 1.0f,
    0.0f, 0.0f, 1.0f
};

1 个答案:

答案 0 :(得分:1)

绑定程序(source)后必须调用

glUniform..()。所以以下内容应该有效:

glClear(GL_COLOR_BUFFER_BIT);

glUseProgram(shaders[TRIANGLE]);
glUniformMatrix3fv(index2, 1, true, value_ptr(projectionMatrix));
glBindVertexArray(vaos[TRIANGLE]);
glDrawArrays(GL_TRIANGLES, 0, tbufindex/sizeof(glm::vec3));

glUseProgram(shaders[LINE]); // If I comment out this line both objects will be drawn
glUniformMatrix3fv(index, 1, true, value_ptr(projectionMatrix));
glBindVertexArray(vaos[LINE]);
glDrawArrays(GL_LINE_STRIP, 0, sizeof(vertices_position)/sizeof(glm::vec3));