获取对象索引

时间:2014-03-27 14:42:03

标签: opengl-es-2.0 mesh vertex-buffer indices

我从.obj文件加载了网格

o Plane_Plane.002
v 1.000000 0.000000 1.000000
v -1.000000 0.000000 1.000000
v 1.000000 0.000000 -1.000000
v -1.000000 0.000000 -1.000000
vt 0.000100 0.000100
vt 0.999900 0.000100
vt 0.999900 0.999900
vt 0.000100 0.999900
vn 0.000000 1.000000 0.000000
usemtl None
s off
f 2/1/1 1/2/1 3/3/1
f 4/4/1 2/1/1 3/3/1

我用数据顺序创建顶点缓冲区:

PosX,PosY,PosZ,NormX,NormY,NormZ,TexX,TexY

现在我必须生成索引以绘制此平面,如0,1,2,0,2,3或0,1,2,3,4,5,因为我已在顶点缓冲区中创建了6个顶点。我真的很困惑:(

1 个答案:

答案 0 :(得分:0)

您可以使用以顶点为键,索引为值为
的地图 从int counter = 0开始,遍历所有顶点,如果地图已经包含此顶点,则为该顶点=计数器的索引然后设置map [vertex] = counter ++

否则index = map [vertex]

当然你会超载<用于顶点的任何类型的运算符,因为映射期望其键可比较

以下是统一顶点中地图用法的示例代码

#include <iostream>
#include <map>

using namespace std;

struct Point
{
    float x;
    float y;
    float z;

    Point()
    {

    }

    Point(float _x, float _y, float _z)
    {
        x = _x;
        y = _y;
        z = _z;
    }

    bool operator<( const Point& p ) const
    {
        if(x < p.x)
            return true;
        if(y < p.y)
            return true;
        if(z < p.z)
            return true;
        return false;
    }
};

void main()
{
    Point p[4];
    p[0] = Point(0,0,0);
    p[1] = Point(1,1,1);
    p[2] = Point(0,0,0);
    p[3] = Point(1,1,1);

    std::map<Point, int> indicesMap;
    int counter = 0;

    for(int i=0;i<4;i++)
    {
        if(indicesMap.find(p[i]) == indicesMap.cend()) // new vertex
        {
            indicesMap[p[i]] = counter++;
        }
    }

    for(int i=0;i<4;i++)
    {
        std::cout << indicesMap[p[i]] << std::endl;
    }
}

输出将为0 0
1
0
1

因为p [2]是p [0]而p [3]是p [1]