好吧,所以我想学习OpenGL。我已经成功地遵循了一个例子来渲染一个三角形。所以我试着继续前进,而不是使用示例中提供的顶点,我尝试从文件中读取顶点(任意数量的顶点)。由于它是任意的,我读入std::vector
,然后尝试将其分配给数组以传递给glBufferData
。 FWIW,我想画GL_LINE_STRIP
,而不是GL_TRIANGLES
。我的程序一秒钟,然后弹出的窗口中运行一个错误显示:OpenGL VBO问题
Debug assertion failed...
然后它说...Expression: vector subscript out of range
我要发布的代码是示例程序呈现一个三角形,但是,我已经将我从文件中读取的尝试(导致错误的代码)注释掉了。所以你可以看到它出错的地方。在MY版本中唯一真正改变的是改变阵列中的硬编码顶点以便从输入读取,然后在drawArray函数中,我将GL_TRIANGLES
更改为GL_LINE_STRIP
。我知道我正在做一些非常愚蠢的事情,而我错过了它,我只是很困惑于OpenGL中的非即时模式(我知道极端noob)。总之,这里是代码:
void CreateVBO(void)
{
/*
string line;
int count = 0;
vector<GLfloat> vertices;
vector<GLfloat> colors;
ifstream myfile("C:\\Users\\Andrew\\Documents\\Visual Studio 2013\\Projects\\Control\\Control\\bin\\Debug\\GeoTemp.test");
if (myfile.is_open())
{
while (getline(myfile, line))
{
float temp = (float)atof(line.c_str());
if (count == 3)
{
vertices.push_back(1.0);
colors.push_back(1.0);
count = 0;
}
else
{
vertices.push_back(temp);
colors.push_back(0.0);
count++;
}
//cout << line << '\n';
}
myfile.close();
}
GLfloat* Vertices = &vertices[0];
GLfloat* Colors = &colors[0];
*/
GLfloat Vertices[] = {
-0.8f, -0.8f, 0.0f, 1.0f,
0.0f, 0.8f, 0.0f, 1.0f,
0.8f, -0.8f, 0.0f, 1.0f
};
GLfloat Colors[] = {
1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f
};
GLenum ErrorCheckValue = glGetError();
glGenVertexArrays(1, &VaoId);
glBindVertexArray(VaoId);
glGenBuffers(1, &VboId);
glBindBuffer(GL_ARRAY_BUFFER, VboId);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);
//glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(GLfloat), &vertices[0], GL_STATIC_DRAW);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glGenBuffers(1, &ColorBufferId);
glBindBuffer(GL_ARRAY_BUFFER, ColorBufferId);
glBufferData(GL_ARRAY_BUFFER, sizeof(Colors), Colors, GL_STATIC_DRAW);
//glBufferData(GL_ARRAY_BUFFER, colors.size()*sizeof(GLfloat), &colors[0], GL_STATIC_DRAW);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);
ErrorCheckValue = glGetError();
if (ErrorCheckValue != GL_NO_ERROR)
{
fprintf(
stderr,
"ERROR: Could not create a VBO: %s \n",
gluErrorString(ErrorCheckValue)
);
exit(-1);
}
}
您是否在'GLfloat * Vertices =&vertices [0]'行之前验证了'!vertices.empty()&&!colors.empty()'? – genpfault