glDrawArrays导致内存不足

时间:2015-03-24 11:33:11

标签: c++ qt opengl vbo vao

我正在使用VAO和VBO构建一个使用OpenGL的Qt应用程序。我有一个简单的参考网格,我想用以下代码绘制

void ReferenceGrid::initialize()
{
   // Buffer allocation and initialization
   Float3Array vertices;
   for (float pos = -GridSide; pos <= GridSide; pos += 1.0) { 
       // X line
       vertices.push_back(Float3(pos, -GridSide, 0.0f));
       vertices.push_back(Float3(pos,  GridSide, 0.0f));

       // Y line
       vertices.push_back(Float3(-GridSide, pos, 0.0f));
       vertices.push_back(Float3( GridSide, pos, 0.0f));

       LineCount += 2;
   }

   s_gridVao.create();
   s_gridVao.bind();

   s_gridBuffer.create();
   s_gridBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw);
   s_gridBuffer.allocate(vertices.data(), vertices.memorySize());


   // Shader allocation and initialization
   s_gridShader.create();
   if (!s_gridShader.addShaderFromSourceFile(QOpenGLShader::Vertex, ":/shaders/Grid.vert")) {
       qWarning() << "Cannot grid vertex shader";
   }

   if (!s_gridShader.addShaderFromSourceFile(QOpenGLShader::Fragment, ":/shaders/Grid.frag")) {
       qWarning() << "Cannot grid fragment shader";
   }

   if (!s_gridShader.link()) {
       qWarning() << "Cannot link grid shader";
   }

   s_gridBuffer.bind();
   s_gridShader.enableAttributeArray("vertexPosition");
   s_gridShader.setAttributeBuffer("vertexPosition", GL_FLOAT, 0, 3);
   s_gridBuffer.release();

   s_gridShader.release();

   s_gridVao.release();
}


void ReferenceGrid::draw()
{
   s_gridVao.bind();

   s_gridShader.bind();
   s_gridBuffer.bind();
   glfuncs->glDrawArrays(GL_LINES, 0, LineCount);
   // Return GL_OUT_OF_MEMORY
   assert(glfuncs->glGetError() == GL_NO_ERROR);

   s_gridBuffer.release();
   s_gridShader.release();
   s_gridVao.release();
 }

问题是在调用glDrawArrays后返回错误(GL_OUT_OF_MEMORY)。我无法理解发生了什么。

有没有人遇到过这个问题并且有解决方案?

1 个答案:

答案 0 :(得分:0)

我忘了在分配之前绑定缓冲区。我认为Qt会自动执行此操作,但我错了。所以正确的做法是:

s_gridBuffer.create();
s_gridBuffer.setUsagePattern(QOpenGLBuffer::StaticDraw);
s_gridBuffer.bind();
s_gridBuffer.allocate(vertices.data(), vertices.memorySize());

我找到了一个关于这个主题的好教程,http://www.kdab.com/opengl-in-qt-5-1-part-2/