我编写了这个“模型”类来加载 .obj 文件并在 VBO 中为它们分配数据。它的代码是这样的:(注意它是如何不使用 VAO 的)
class Model {...}
void Model::LoadOBJ(const char *file)
{
//load vertices, normals, UVs, and put them all in _vec, which is a private data member of std::vector<glm::vec3>
...
//if an .obj file is loaded for the first time, generate a buffer object and bind it
if(glIsBuffer(_vbo) == GL_FALSE)
{
glGenBuffers(1, &_vbo);//_vbo is a private data member
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
}
//load the data in the array buffer object
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * _vec.size(), &_vec[0][0], GL_STATIC_DRAW);
}
void Model::Draw()
{
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glDrawArrays(GL_TRIANGLES, 0, _numVertices);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
我曾经认为下一个代码可以很好地渲染两个不同的对象:
void init()
{
//vao dummy (?)
GLuint VAO;
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
//load 3d models
Model cube = load("cube.obj");
Model cow = load("cow.obj");
//the next two lines should be valid for both objects?
glVertexAttribPointer(prog.GetAttribLocation("vertex"), 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(prog.GetAttribLocation("vertex"));
}
void render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//draw cube:
//some matrix transformations
...
cube.Draw();
//draw cow:
//some matrix transformations
...
cow.Draw()
glutSwapBuffers();
}
但事实证明,OpenGL 只会绘制两只牛或两个立方体。(取决于我在 init() 中最后加载的模型)
顺便说一句,我很确定在第一张图片中,opengl 确实尝试绘制了两只奶牛,但是调用 glDrawArrays() 函数时使用了立方体所需的顶点数量。
那么我错过了什么?我是否需要为每个缓冲区对象或类似的东西使用不同的 VAO?