用c ++构建UV球体

时间:2014-10-25 16:07:33

标签: c++ qt graphics 3d geometry

我尝试使用Qt Creator在C ++中制作UV球体,我想在不使用openGL命令的情况下构建球体。我试图将顶点添加到lObject,然后添加法线和三角形。球体的半径为1.第一个问题是它在绘制时不会渲染球体,所以也许我没有添加正确的顶点或者我没有正确地添加三角形。对我做错的任何帮助都会很棒。

以下是我尝试的内容:

NodeObject* ObjectFactory::buildSphere(int slices, int stacks)
{ 
    // Allocate a new node object
    NodeObject* lObject = new NodeObject();

    for(int i=0; i<stacks; i++)
    {
        double lnum1 = 360.0/stacks;
        double lTheta = ((double)i)*(lnum1*(M_PI/180.0));       
        double lNextTheta = ((double)(i+1))*lnum1*(M_PI/180.0);    

        for(int j=0; j<slices; j++)
        {
            double lnum2 = 180.0/slices;
            double lPhi = ((double)i)*(lnum2*(M_PI/180.0));     
            double lNextPhi = ((double)(i+1))*lnum1*(M_PI/180.0);

            lObject->addVertex(0.0, 1.0, 0.0); //Top

            lObject->addVertex(sin(lTheta)*cos(lPhi), sin(lTheta)*sin(lPhi), cos(lTheta));
            lObject->addVertex(sin(lNextTheta)*cos(lNextPhi), sin(lNextTheta)*sin(lNextPhi),    cos(lNextTheta));

            lObject->addVertex(sin(lTheta)*cos(lPhi), -(sin(lTheta)*sin(lPhi)), cos(lTheta));
            lObject->addVertex(sin(lNextTheta)*cos(lNextPhi), -(sin(lNextTheta)*sin(lNextPhi)),              cos(lNextTheta));

            lObject->addVertex(0.0, -1.0, 0.0); //Bottom

            lObject->addNormal(0.0,1.0,0.0);
            lObject->addNormal(0.0,-1.0,0.0);
            lObject->addNormal(sin(lTheta)*cos(lPhi),sin(lTheta)*sin(lPhi), cos(lTheta));

            for(int k=0; k<pSlices*6; k++)
            {
                if(i==0) { lObject->addTriangle(0,1,2,0,0,0); }
                else if(i+1 == stacks) {lObject->addTriangle(2,0,1,0,0,0); }
                else
                {
                    lObject->addTriangle(k, k+1, k+2,k,k+1,k+2);
                }
            }
        }

    }
    return lObject;
}

1 个答案:

答案 0 :(得分:0)

在你的第三个for循环中,pSlices的值是多少?另外,为什么要为每个堆栈添加顶部和底部?

为了更好的练习,首先生成顶点,然后执行其他操作。

您可以使用简单的数据结构来保存数据,例如,在内部循环处生成一层顶点。:

QVector3D sphereVertices[stacks][slices];

对于第一层填充(0.0,1.0,0.0); 对于最后一层,用(0.0,-1.0,0.0)填充;

然后迭代顶点以计算法线并在CCW中创建三角形。

for ( int i = 0; i < stacks -1; i++){ //-1 is due to we are using the next stack to create the face
    for ( int j = 0; j < slices -1; j++){ //we are also using the next slice
        //Add these vertex indices
        //First triangle indices
        //i*slices + j, (i+1)*slices + j, (i+1)*slices + j + 1
        //Second triangle indices
        //i*slices + j, (i+1)*slices + j + 1, i*slices + j + 1
        //Furthermore you can calculate triangle normal by using these vertices
        //https://www.opengl.org/wiki/Calculating_a_Surface_Normal
    }
}