在opengl中加载obj文件时,向量下标超出范围

时间:2016-01-05 03:19:09

标签: c++ opengl

我正在尝试在线阅读关于opengl的教程:http://www.opengl-tutorial.org/beginners-tutorials/tutorial-7-model-loading

基本上我在线跟踪代码,加载代码正在运行,但它在C中,所以我尝试将其转换为C ++

这就是我提出的:

using namespace std;
bool loadOBJ(const char * path, std::vector<glm::vec3> & out_vertices)
{
    vector<glm::vec3> temp_vertices;
    vector<unsigned int> vertexIndices, uvIndices;
    ifstream file(path);
    string lineHeader;
    if (file.is_open())
{

}
else
{
    printf("Impossible to open the file ! Are you in the right path ?\n");
    getchar();
    return 0;
}

while (!file.eof())
{
    file >> lineHeader;
    if (lineHeader.compare("v") == 0)
    {
        // load vertex
    }
    else if (lineHeader.compare("f") == 0)
    {
        // follow the fix

        vertexIndices.push_back(vertexIndex[0]);
        vertexIndices.push_back(vertexIndex[1]);
        vertexIndices.push_back(vertexIndex[2]);
        for (int i = 0; i < 3; i++)
        {
            cout << vertexIndex[i] << " ";
        }
        cout << endl;
    }

}

for (unsigned int i = 0; i < vertexIndices.size(); i++)
{

    // Get the indices of its attributes
    unsigned int vertexIndex = vertexIndices[i];

    // Get the attributes thanks to the index
    glm::vec3 vertex = temp_vertices[vertexIndex - 1];

    // Put the attributes in buffers
    out_vertices.push_back(vertex);

}
return true;
}

我收到此错误:

  

矢量下标超出范围。

我知道我搞砸了vector,但我不确定是什么问题。

2 个答案:

答案 0 :(得分:0)

您正在错误地阅读该文件。如果你看一下page you linked to

8/11/7 describes the first vertex of the triangle
7/12/7 describes the second vertex of the triangle
6/10/7 describes the third vertex of the triangle (duh)
For the first vertex, 8 says which vertex to use. So in this case, -1.000000 1.000000 -1.000000 (index start to 1, not to 0 like in C++)
11 says which texture coordinate to use. So in this case, 0.748355 0.998230
7 says which normal to use. So in this case, 0.000000 1.000000 -0.000000

因此第一个示例行中的11和7是“纹理坐标”和“正常”。但是,您只需将这些放入要打印的顶点列表中。当您尝试打印顶点11时,程序崩溃,因为只有8个顶点。

快速修复,删除以下两行:

    vertexIndices.push_back(vertexIndex[1]);
    vertexIndices.push_back(vertexIndex[2]);

更完整的修复,删除这两行并添加一项检查以确保数据文件有效:

 // Get the attributes thanks to the index
 if (vertexIndex >= temp_vertices.size())
 {
    cout << "Can't get vertex " << vertexIndex;
    return 0;
 }
 glm::vec3 vertex = temp_vertices[vertexIndex - 1];

答案 1 :(得分:0)

我解决了这个问题

        getline(file, tempBlock, '/');
        vertexIndex[0] = stoi(tempBlock);
        getline(file, tempBlock, '/');
        // Uv0
        file >> tempBlock;
        // normal0
        getline(file, tempBlock, '/');
        vertexIndex[1] = stoi(tempBlock);
        getline(file, tempBlock, '/');
        // Uv1
        file >> tempBlock;
        // normal1
        getline(file, tempBlock, '/');
        vertexIndex[2] = stoi(tempBlock);
        getline(file, tempBlock, '/');
        // Uv2
        file >> tempBlock;
        // normal2

基本上我正在读取顶点错误