2

我一直在尝试使用ASSIMP加载Wavefront obj模型。但是,我无法让 mtl 材料颜色起作用。我知道如何加载,但是,我不知道如何为每个顶点获取相应的颜色。(Kd rgb)

usemtl material_11
f 7//1 8//1 9//2
f 10//1 11//1 12//2

例如,上面的 Wavefront obj 片段意味着这些顶点使用 material_11。

Q:那么如何获取每个顶点对应的材质呢?

错误

Wavefront obj材质不在正确的顶点中:

原始模型(使用 ASSIMP 模型查看器渲染): 在此处输入图像描述

用我的代码渲染的模型: 在此处输入图像描述

代码:

我用于加载 mtl 材料颜色的代码:

std::vector<color4<float>> colors = std::vector<color4<float>>();

                            ...

for (unsigned int i = 0; i < scene->mNumMeshes; i++)
{
    const aiMesh* model = scene->mMeshes[i];
    const aiMaterial *mtl = scene->mMaterials[model->mMaterialIndex];

    color4<float> color = color4<float>(1.0f, 1.0f, 1.0f, 1.0f);
    aiColor4D diffuse;
    if (AI_SUCCESS == aiGetMaterialColor(mtl, AI_MATKEY_COLOR_DIFFUSE, &diffuse))
        color = color4<float>(diffuse.r, diffuse.g, diffuse.b, diffuse.a);
    colors.push_back(color);

                            ...
}

创建顶点的代码:

vertex* vertices_arr = new vertex[positions.size()];
for (unsigned int i = 0; i < positions.size(); i++)
{
    vertices_arr[i].SetPosition(positions.at(i));
    vertices_arr[i].SetTextureCoordinate(texcoords.at(i));
}

// Code for setting vertices colors (I'm just setting it in ASSIMP vertices order, since I don't know how to set it in the correct order).
for (unsigned int i = 0; i < scene->mNumMeshes; i++)
{
    const unsigned int vertices_size = scene->mMeshes[i]->mNumVertices;
    for (unsigned int k = 0; k < vertices_size; k++)
    {
        vertices_arr[k].SetColor(colors.at(i));
    }
}

编辑

看起来模型顶点位置也没有正确加载。即使我禁用面部剔除并更改背景颜色。

在此处输入图像描述

4

1 回答 1

2

忽略与绘制调用数量和额外存储、带宽和顶点颜色处理相关的问题,

看起来vertex* vertices_arr = new vertex[positions.size()];您正在创建一个大数组来保存整个模型(它有许多网格,每个网格都有一种材料)。假设您的第一个循环是正确的并且positions包含模型所有网格的所有位置。第二个循环开始为网格中的每个顶点复制网格颜色。但是,vertices_arr[k]总是从零开始,并且需要在前一个网格的最后一个顶点之后开始。相反,请尝试:

int colIdx = 0;
for (unsigned int i = 0; i < scene->mNumMeshes; i++)
{
    const unsigned int vertices_size = scene->mMeshes[i]->mNumVertices;
    for (unsigned int k = 0; k < vertices_size; k++)
    {
        vertices_arr[colIdx++].SetColor(colors.at(i));
    }
}
assert(colIdx == positions.size()); //double check

正如您所说,如果几何图形未正确绘制,则可能positions不包含所有顶点数据。也许与上述代码类似的问题?另一个问题可能是加入每个网格的索引。索引都需要更新到vertices_arr数组中新顶点位置的偏移量。虽然现在我只是在猜测。

于 2014-12-18T04:17:36.907 回答