Search code examples
c++algorithmvectorgeometryindices

What is the difference of those code snippets?


The following code snippets are my attempts to get the triangles from indices and vertices. The indices vector contains the number of the vertex. The vertices vector contains the coordinates where three of them make one vertex. Together three vertices make up a triangle.

The first snippet works but I would like to not use the additional vector.

vector<float> coords;
for(unsigned int i : indices)
{
    coords.push_back(vertices[3 * i + 0]);
    coords.push_back(vertices[3 * i + 1]);
    coords.push_back(vertices[3 * i + 2]);
}
for(unsigned int i = 0; i < coords.size(); i += 9)
{
    triangles->addTriangle(
        btVector3(coords[i + 0], coords[i + 1], coords[i + 2]),
        btVector3(coords[i + 3], coords[i + 4], coords[i + 5]),
        btVector3(coords[i + 6], coords[i + 7], coords[i + 8])
    );
}

The second snippet doesn't work, it results in an access violation.

float coords[9];
for(unsigned int i = 0; i < indices.size(); i += 9)
{
    for(int n = 0, j = 0; j < 3; ++j)
        for(int k = 0; k < 3; ++k, ++n)
            coords[n] = vertices[3 * indices[i + n] + k];

    triangles->addTriangle(
        btVector3(coords[0], coords[1], coords[2]),
        btVector3(coords[3], coords[4], coords[5]),
        btVector3(coords[6], coords[7], coords[8])
    );
}

I haven't found the difference. Why isn't the second snippet working?


Solution

  • coords[n] = vertices[3 * indices[i + n] + k];
    

    should be

    coords[n] = vertices[3 * indices[i + j] + k];