当不使用某些顶点属性时,glDrawElements崩溃

glDrawElements crashes when not using certain vertex attributes

本文关键字:属性 glDrawElements 崩溃 顶点      更新时间:2023-10-16

在我的OpenGL程序中我有两个着色器。一个渲染纹理,另一个渲染纯色。在编译和链接着色器之后,我启用了一个纹理坐标顶点属性数组,这取决于着色器是否包含该属性。

//This code is called after the shaders are compiled.
//Get the handles
textureU = glGetUniformLocation(program,"texture");
tintU = glGetUniformLocation(program,"tint");
viewMatrixU = glGetUniformLocation(program,"viewMatrix");
transformMatrixU = glGetUniformLocation(program,"transformMatrix");
positionA = glGetAttribLocation(program,"position");
texcoordA = glGetAttribLocation(program,"texcoord");
//Detect if this shader can handle textures
if(texcoordA < 0 || textureU < 0) hasTexture = false;
else hasTexture = true;
//Enable Attributes
glEnableVertexAttribArray(positionA);
if(hasTexture) glEnableVertexAttribArray(texcoordA);

如果我渲染一个有纹理的item, verts中的每个元素包含5个值(x,y,z,tx,ty),但如果项目不是纹理,verts中的每个元素只包含3个值(x,y,z)。

这里是问题:当第一个item渲染在GL上下文中没有纹理,glDrawElements segfault !但是,如果渲染的第一个项目确实有纹理,它就会正常工作,并且在有纹理的项目之后的任何非纹理项目都可以正常工作(也就是说,直到创建新的上下文)。

这段代码呈现了一个item

glBindBuffer(GL_ARRAY_BUFFER,engine->vertBuffer);
glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat)*item->verts.size(),&item->verts[0],GL_DYNAMIC_DRAW);
item->shader->SetShader();
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,engine->elementBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(GLuint) * item->indicies.size(),&item->indicies[0],GL_DYNAMIC_DRAW);
if(item->usingTexture)
    item->shader->SetTexture(item->texture->handle);
glUniformMatrix4fv(item->shader->transformMatrixU,1,GL_TRUE,&item->matrix.contents[0]);
glUniformMatrix4fv(item->shader->viewMatrixU,1,GL_TRUE,&item->batch->matrix.contents[0]);
glUniform4f(item->shader->tintU,item->color.x,item->color.y,item->color.z,item->color.w);
glDrawElements(GL_TRIANGLES,item->indicies.size(),GL_UNSIGNED_INT,0); //segfault

这是上面看到的设置着色器的函数。

glUseProgram(program); currentShader = program;
GLsizei stride = 12;
if(hasTexture) stride = 20;
glVertexAttribPointer(positionA,3,GL_FLOAT,GL_FALSE,stride,0);
if(hasTexture)
    glVertexAttribPointer(texcoordA,2,GL_FLOAT,GL_FALSE,stride,(void*)12);

据我所知,这个问题在英特尔集成显卡上并不明显,它似乎相当宽松。

编辑:如果知道它是有用的,我使用GLFW和GLEW

尝试在draw调用后添加相应的 glDisableVertexAttribArray()s:

glEnableVertexAttribArray(positionA);
if(hasTexture) glEnableVertexAttribArray(texcoordA);
// draw
glDisableVertexAttribArray(positionA);
if(hasTexture) glDisableVertexAttribArray(texcoordA);

问题是我在编译我的着色器后启用了顶点属性数组。我不应该在这里纵容他们。

我在编译着色器时启用了texcoord属性,但由于第一个项目没有使用它,glDrawElements会出现分段错误。

我通过在设置着色器时启用属性来修复这个问题。