2

My goal is to render a list of segments using VBOs with different colors and if possible with different widths.

Each vertex is defined by:

class Vector2f {
public:
    float x, y;
};

The list of segments consists in pairs of vertexes that define a segment.

Then I initialize the VBO:

glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vector2f) * segments.size(), &segments[0], GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

And then I draw using:

glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, sizeof(Vector2f), (void*)(sizeof(float) * 0));
glColor3f(0.0f, 1.0f, 0.0f);
glDrawArrays(GL_LINES, 0, segments.size());
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);

In my example, I want to give to each segment a color. The color is previously defined and can only be 1 from 3 options. How can I do it? And can I optimize it by using indexes for color instead of repeating them all over?

If so, how?

Also, is it possible to define the width of each individual segment?

genpfault
  • 51,148
  • 11
  • 85
  • 139
gdf31
  • 387
  • 1
  • 4
  • 11

1 Answers1

3

How can I do it?

Extend your vertex struct to contain color values:

class Vector2f
{
public:
    float x, y;
    unsigned char r, g, b;
};

And use GL_COLOR_ARRAY + glColorPointer():

glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(2, GL_FLOAT, sizeof(Vector2f), offsetof( Vector2f, x ) );
glColorPointer(3, GL_UNSIGNED_BYTE, sizeof(Vector2f), offsetof( Vector2f, r ) );
glDrawArrays(GL_LINES, 0, segments.size());
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);

Also, is it possible to define the width of each individual segment?

Not really with fixed-function. You either end up with a glLineWidth() + draw-call per segment (losing the performance benefit of batching draw-calls) or converting the line into triangle geometry on the CPU (significantly more complicated).

genpfault
  • 51,148
  • 11
  • 85
  • 139
  • So I cannot optimize the color array using indexes? – gdf31 Nov 02 '17 at 15:23
  • @gdf31: Not really, OpenGL doesn't allow for a separate index array for each attribute. – genpfault Nov 02 '17 at 15:30
  • @gdf31: Honestly if you're targeting desktop OpenGL vertex data is just microscopic compared to even a handful of textures. – genpfault Nov 02 '17 at 15:31
  • Can I have a std;;vector with the Vector2f of the position and then a Vector3f color and so on? How to deal with the strides in this case? – gdf31 Nov 09 '17 at 15:54
  • @gdf31: Yup, totally doable. In that case you can use `0` for the `stride`s since your values are tightly-packed. – genpfault Nov 09 '17 at 16:25