Creating spherical meshes with Direct x?

筅森魡賤 提交于 2020-01-04 15:17:13

问题


How do you go about creating a sphere with meshes in Direct-x? I'm using C++ and the program will be run on windows, only.

Everything is currently rendered through an IDiRECT3DDEVICE9 object.


回答1:


You could use the D3DXCreateSphere function.




回答2:


There are lots of ways to create a sphere.

One is to use polar coordinates to generate slices of the sphere.

struct Vertex
{
    float x, y, z;
    float nx, ny, nz;
};

Given that struct you'd generate the sphere as follows (I haven't tested this so I may have got it slightly wrong).

std::vector< Vertex > verts;
int count   = 0;
while( count < numSlices )
{
    const float phi = M_PI / numSlices;
    int count2  = 0;
    while( count2 < numSegments )
    {
        const float theta   =  M_2PI / numSegments
        const float xzRadius = fabsf( sphereRadius * cosf( phi ) );

        Vertex v;
        v.x = xzRadius * cosf( theta );
        v.y = sphereRadius * sinf( phi );
        v.z = xzRadius * sinf( theta );

        const float fRcpLen = 1.0f / sqrtf( (v.x * v.x) + (v.y * v.y) + (v.z * v.z) );
        v.nx    = v.x * fRcpLen;
        v.ny    = v.y * fRcpLen;
        v.nz    = v.z * fRcpLen;

            verts.push_back( v );
        count2++;
    }
    count++;
}

This is how D3DXCreateSphere does it i believe. Of course the code above does not form the faces but thats not a particularly complex bit of code if you set your mind to it :)

The other, and more interesting in my opinion, way is through surface subdivision.

If you start with a cube that has normals defined the same way as the above code you can recursively subdivide each side. Basically you find the center of the face. Generate a vector from the center to the new point. Normalise it. Push the vert out to the radius of the sphere as follows (Assuming v.n* is the normalised normal):

v.x = v.nx * sphereRadius;
v.y = v.ny * sphereRadius;
v.z = v.nz * sphereRadius;

You then repeat this process for the mid point of each edge of the face you are subdividing.

Now you can split each face into 4 new quadrilateral faces. You can then subdivide each of those quads into 4 new quads and so on until you get to the refinement level you require.

Personally I find this process provides a nicer vertex distribution on the sphere than the first method.



来源:https://stackoverflow.com/questions/1695421/creating-spherical-meshes-with-direct-x

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!