Domanda

Recently I started to learn OpenGL and I am beginning to learn the newer assets of it. For a while now I've been trying to work with VBOs, to draw a simple cube from a vertex point array. I am having trouble rendering it and understanding some of the arguments in the functions. It throws no errors but nothing is in my view.

float cubeVertPoints[72]; //An array containing the vertex points

Here is my VBO init

void loadBufferData()
{
    glGenBuffers(1, &cubeVBO);
    glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertPoints[0])*3, &cubeVertPoints[0], GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(cubeVertPoints[0])*3, (void*)sizeof(GL_FLOAT));
} 

Drawing

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); 
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(cubeVertPoints[0])*3, (void*)sizeof(GL_FLOAT));

    glDrawArrays(GL_TRIANGLES, 0, 1); 

    glDisableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
È stato utile?

Soluzione

You are not transferring all your data into the vertex buffer. The 2nd parameter of glBufferData takes the size of all of your vertex data in bytes. You should set it to sizeof(vertex) * vertex_count.

Also, calling glEnableVertexAttribArray and glVertexAttribPointer in loadBufferData is redundant. You should call them only in your rendering function.

Your second problem is with glVertexAttribPointer. You are not passing the correct offset to your vertex position data in your vertex data "structure". Since your vertices only consist of positions, this offset should be 0. If you would have positions and colors for each vertex, these offset could be 0 (for position) and sizeof(float) * 3 (for color, because you have 3 coordinates).

Finally, you only draw a single vertex. You should draw 72/3=24 if your cube has 24 vertices.

I think you can make your life easier by defining an actual structure for your vertices, like so:

struct Vertex
{
  float position[3];
};

Then, you can compute offsets for each of your vertex positions, colors, etc, with (GLvoid*)(&((Vertex*)NULL)->position).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top