Assimp访问违反现有aiVector3D

时间:2015-01-16 01:16:52

标签: c++ access-violation assimp

我使用以下代码使用Assimp加载.obj文件。 TextureCoordinates出了点问题。我尝试访问的aiVector3D存在,但只要我将值存储在临时变量中,它就会崩溃我的应用程序。

这是我使用的代码:

    Assimp::Importer importer;

    const aiScene* scene = importer.ReadFile(filename,
        aiProcess_CalcTangentSpace |
        aiProcess_Triangulate |
        aiProcess_JoinIdenticalVertices |
        aiProcess_SortByPType);

    if (!scene)
    {
        printf("[ASSIMP] ");
        printf(importer.GetErrorString());
        printf("\n");
        return nullptr;
    }

    Mesh* newMesh = new Mesh();
    unsigned int vertexCount            = scene->mMeshes[0]->mNumVertices;
    unsigned int triangleCount          = scene->mMeshes[0]->mNumFaces;
    bool hasUv                          = scene->mMeshes[0]->HasTextureCoords(0);
    newMesh->vertexCount                = vertexCount;
    newMesh->triangleCount              = triangleCount;
    newMesh->m_Vertices                 = new Vertex[vertexCount];
    newMesh->m_Triangles                = new Triangle[triangleCount];

    for (unsigned int i = 0; i < vertexCount; i++) {
        aiVector3D vertexPosition       = scene->mMeshes[0]->mVertices[i];
        aiVector3D vertexNormal         = scene->mMeshes[0]->mNormals[i];
        newMesh->m_Vertices[i].pos      = glm::vec3(vertexPosition.x, vertexPosition.y, vertexPosition.z);
        newMesh->m_Vertices[i].normal   = glm::vec3(vertexNormal.x, vertexNormal.y, vertexNormal.z);
        if (hasUv) {
            aiVector3D uvCoordinates    = scene->mMeshes[0]->mTextureCoords[i][0];
            printf("uvCoordinates: %f %f %f\n", uvCoordinates.x, uvCoordinates.y, uvCoordinates.z);
            newMesh->m_Vertices[i].u    = uvCoordinates.x;
            newMesh->m_Vertices[i].v    = uvCoordinates.y;
        }
    }

    for (unsigned int i = 0; i < triangleCount; i++) {
        aiFace face                     = scene->mMeshes[0]->mFaces[i];
        for (int j = 0; j < 3; j++) {
            Triangle* tri               = &newMesh->m_Triangles[i];
            tri->vertex[j]              = &newMesh->m_Vertices[face.mIndices[j]];
            if (tri->vertex[0]->normal.y == 1.0f || tri->vertex[0]->normal.y == -1.0f) {
                tri->color              = glm::vec3(0.2f, 0.2f, 0.2f);
            }
            else
            {
                tri->color              = glm::vec3(1.0f, 0.0f, 0.0f);
            }
        }
    }

它在printf("uvCoordinates: %f %f %f\n", uvCoordinates.x, uvCoordinates.y, uvCoordinates.z);行崩溃,但如果我删除此行,它会在newMesh->m_Vertices[i].u = uvCoordinates.x;崩溃。如果我对printf()发表评论,请将顶点的uv设置为0.0f而不要使用uvCoordinates,它仍然会崩溃newMesh->m_Vertices[i].u = uvCoordinates.x;行。如果我将printf()取消注释,则会打印uvCoordinates的值,但会在之后引发访问冲突。

我诚实地说出了这些想法。这里a screenshot显示了我的解释。

1 个答案:

答案 0 :(得分:0)

scene->mMeshes[0]->mTextureCoords[i][0];是set i的第一个纹理坐标。你想要的是得到第一组纹理坐标 - 所以它应该是scene->mMeshes[0]->mTextureCoords[0][i];