没有GLUT和剔除问题的OpenGL球体

时间:2013-12-02 23:16:34

标签: c++ opengl

我正在修改此答案Creating a 3D sphere in Opengl using Visual C++中提供的优秀代码以满足我的需求,即使用GL_TRIANGLES绘制它并面对这样的剔除:

GLCALL(glEnable(GL_CULL_FACE));
GLCALL(glCullFace(GL_BACK));
GLCALL(glFrontFace(GL_CCW));

我设法使指数适用于三角形,但我不知道如何消除剔除面部问题;事实上,它使用我在下面提到的indice设置来剔除错误的面孔:

bool CreateSphereData(const float radius, const uint32_t rings, const uint32_t sectors, std::vector<float>& vertexData, std::vector<float>& normalData, std::vector<float>& texcoordData, std::vector<uint32_t>& indiceData)
{
    if (radius <= 0 || rings <= 0 || sectors <= 0)
        return false;

    const float R = 1.0f / (float)(rings - 1);
    const float S = 1.0f / (float)(sectors - 1);
    const float pi = boost::math::constants::pi<float>();
    const float pi_2 = pi / 2;

    vertexData.resize(rings * sectors * 3);
    normalData.resize(rings * sectors * 3);
    texcoordData.resize(rings * sectors * 2);
    auto v = vertexData.begin();
    auto n = normalData.begin();
    auto t = texcoordData.begin();
    for (uint32_t r = 0; r < rings; r++)
    {
        for (uint32_t s = 0; s < sectors; s++)
        {
            const float y = sin(-pi_2 + pi * r * R);
            const float x = cos(2 * pi * s * S) * sin(pi * r * R);
            const float z = sin(2 * pi * s * S) * sin(pi * r * R);

            *t++ = s*S;
            *t++ = r*R;

            *v++ = x * radius;
            *v++ = y * radius;
            *v++ = z * radius;

            *n++ = x;
            *n++ = y;
            *n++ = z;
        }
    }

    indiceData.resize(rings * sectors * 6);
    auto i = indiceData.begin();
    for (uint32_t r = 0; r < rings; r++)
    {
        for (uint32_t s = 0; s < sectors; s++)
        {
            *i++ = (r + 1) * sectors + s;
            *i++ = r * sectors + s;
            *i++ = r * sectors + (s + 1);

            *i++ = (r + 1) * sectors + (s + 1);
            *i++ = (r + 1) * sectors + s;
            *i++ = r * sectors + (s + 1);
        }
    }

    return true;
}

我确信它很简单,但我无法做到。有什么指针吗?

EDIT /解答:

以下索引只需使用上述设置正确绘制:

    indiceData.resize(rings * sectors * 6);
    auto i = indiceData.begin();
    for (uint32_t r = 0; r < rings-1; r++)
    {
        for (uint32_t s = 0; s < sectors-1; s++)
        {
            *i++ = r * sectors + (s + 1);
            *i++ = r * sectors + s;
            *i++ = (r + 1) * sectors + s;

            *i++ = r * sectors + (s + 1);
            *i++ = (r + 1) * sectors + s;
            *i++ = (r + 1) * sectors + (s + 1);
        }
    }

0 个答案:

没有答案