【发布时间】:2014-03-13 18:29:46
【问题描述】:
好的,所以我正在尝试学习 OpenGL。我已经成功地按照一个例子来渲染一个三角形。因此,我尝试继续前进,而不是使用示例中提供的顶点,而是尝试从文件中读取顶点(任意数量的顶点)。因为它是任意的,所以我读入了std::vector,然后尝试将其分配给一个数组以便传递给glBufferData。 FWIW,我想画GL_LINE_STRIP,而不是GL_TRIANGLES。我的程序运行了一秒钟,然后弹出一个错误窗口:
Debug assertion failed... 然后是...Expression: vector subscript out of range
我即将发布的代码是呈现三角形的示例程序,但是,我已经注释掉了我从文件中读取的尝试(给我错误的代码)。所以你可以看到哪里出错了。在 MY 版本中真正改变的唯一事情是更改要从输入读取的数组中的硬编码顶点,然后在 drawArray 函数中将GL_TRIANGLES 更改为GL_LINE_STRIP。我知道我在做一些非常愚蠢的事情而且我很想念它,我只是对 OpenGL 中的非立即模式感到困惑(我知道极端菜鸟)。无论如何,这是代码:
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()?
标签: c++ arrays opengl stdvector vertex-buffer