当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - opengl : can two different vectors bind to the same vertex array object?

问题描述:

I have two vectors,

std::vector col and

std::vector pos,

my shader is as follows:

const GLchar* vertexShaderSource = "#version 330 core\n"

"layout (location = 0) in vec2 position;\n"

"layout (location = 1) in vec3 PColor;\n"

"out vec3 color;\n"

"void main()\n"

"{\n"

"gl_Position = vec4(position.x, position.y, 0.0, 1.0);\n"

"color = PColor;\n"

"}\0";

const GLchar* fragmentShaderSource = "#version 330 core\n"

"out vec4 color;\n"

"in vec4 PColor;\n"

"void main()\n"

"{\n"

"color = PColor;\n"

"}\n\0";

can I do the following to bind both the pos and col to the same VAO

void CreateVertexBuffer()

{

glGenBuffers(1, &posbuffer);

glGenVertexArrays(1, &VAO);

glBindBuffer(GL_ARRAY_BUFFER, posbuffer);

glBufferData(GL_ARRAY_BUFFER, sizeof(int) * pos.size(), &pos.front(), GL_STATIC_DRAW);

glBindVertexArray(VAO);

glVertexAttribPointer(0, 2, GL_INT, GL_FALSE, 2 * sizeof(GL_INT), (GLvoid*)0);

glEnableVertexAttribArray(0);

//glBindVertexArray(0); delete

glGenBuffers(1, &colbuffer);

glBindBuffer(GL_ARRAY_BUFFER, colbuffer);

glBufferData(GL_ARRAY_BUFFER, sizeof(GL_FLOAT) * col.size(), &col.front(), GL_STATIC_DRAW);

glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GL_FLOAT), (GLvoid*)0);

glEnableVertexAttribArray(1);

glBindVertexArray(0);

}

I want to make my program draw a circle, but core dumped, so I think there maybe some problem with my VAO bind. Thanks!

网友答案:
  1. You should generate a VAO before generate VBOs

    glGenVertexArrays(1, &vao[object_id]);
    glBindVertexArray(vao[object_id]);
    
    glGenBuffers(1, &vbo[0]);
    glBindBuffer(target, vbo[0]);
    glBufferData(target, size, data1, dataType);
    glEnableVertexAttribArray(h_Attributes[UV]);
    glVertexAttribPointer(h_Attributes[UV], 2, GL_FLOAT, 0, 0, 0);
    
    glGenBuffers(1, &vbo[1]);
    glBindBuffer(target, vbo[1]);
    glBufferData(target, size, data2, dataType);
    glEnableVertexAttribArray(h_Attributes[POSITION]);
    glVertexAttribPointer(h_Attributes[POSITION], 3, GL_FLOAT, 0, 0, 0);
    
  2. the position vector must be float not int since it will be vec2 in the shader

  3. I am not sure but It seems there is no stride in your array if so don't put 2 * sizeof(GL_INT) and 3 * sizeof(GL_FLOAT)

Update When you draw the object, you must bind the vao you generated

  glBindVertexArray(vao[object_id]);

If you don't update any value of your array, you don't need to bind any vbos in the render loop. However if you need to update the vertices for color or position, you must call those functions.

  glBindVertexArray(vao[object_id]);
  glBindBuffer(target, vbo[object_id]);   
  glBufferData(GL_ARRAY_BUFFER, sizeof(the_array), &the_array[0], GL_DYNAMIC_DRAW);
分享给朋友:
您可能感兴趣的文章:
随机阅读: