I wish to draw two triangles (having one common vertex) with two different colors using an index buffer. How can I do so?
Without using an index buffer, two such triangles can easily be drawn by just repeating the common vertex data. Yes, I can still use an index buffer. But in that case, there is no advantage of using an index buffer. My vertex data is given below:
glm::vec4 positions[] = {
glm::vec4(+0.0f, +0.0f, +0.0f, +1.0f),
glm::vec4(+1.0f, +1.0f, +0.0f, +1.0f),
glm::vec4(-1.0f, +1.0f, +0.0f, +1.0f),
glm::vec4(-1.0f, -1.0f, +0.0f, +1.0f),
glm::vec4(+1.0f, -1.0f, +0.0f, +1.0f)
};
glm::vec4 colors[] = {
glm::vec4(+1.0f, +0.0f, +0.0f, +1.0f),
glm::vec4(+1.0f, +0.0f, +0.0f, +1.0f),
glm::vec4(+1.0f, +0.0f, +0.0f, +1.0f),
glm::vec4(+0.0f, +1.0f, +0.0f, +1.0f),
glm::vec4(+0.0f, +1.0f, +0.0f, +1.0f)
};
int indices[] = {
0, 1, 2,
0, 3, 4
};
I set the attribute layout in the following way:
int positionStride = sizeof(vertex->position) + sizeof(vertex->color);
int positionOffset = 0;
glEnableVertexAttribArray(vertex->POSITION);
glVertexAttribPointer(vertex->POSITION, vertex->position.length(),
GL_FLOAT, GL_FALSE, positionStride, (const void*)positionOffset);
int colorStride = sizeof(vertex->color) + sizeof(vertex->position);
int colorOffset = positionOffset + sizeof(vertex->position);
glEnableVertexAttribArray(vertex->COLOR);
glVertexAttribPointer(vertex->COLOR, vertex->color.length(), GL_FLOAT,
GL_FALSE, colorStride, (const void*)colorOffset);
My vertex class is defined as follows:
class Vertex
{
public:
Vertex();
~Vertex();
enum Attribute
{
POSITION,
COLOR
};
}
Using the above set up I get a perfect red triangle but not the green one as expected. Moreover, despite having only two unique colors, I have to repeat the colors. Since the triangle is the simplest type of geometric object which forms a plane, there are many cases where two adjacent triangles (sharing one or two vertices) need to be rendered with different constant colors. I want to take advantage of using an index buffer and at the same time also want to render two adjacent triangles with constant colors.
Using two unique colors instead of 5 redundant colors will be an added bonus.
Is there any efficient way to accomplish this?
[@ Nicol Bolas: I checked that link even before posting this question. Since I am allowed to use only one index buffer, the trick is really in ordering the indices to fit both the position and color data. However, there are 5 positions and two unique colors. If I arrange the indices to fit the position, I have to define
int indices[] = {
0, 1, 2,
0, 3, 4
};
However, if I wish to fit the color data, I need the indices as
int indices[] = {
0, 1, 2,
3, 3, 4
};
provided I duplicate the colors. ]