3

这是问题的图片:

在此处输入图像描述

这是线框:

线框

正如您从上面的图片中看到的那样,我有一些奇怪的图形问题并且不知道如何修复,我认为代码有问题,尽管没有其他人遇到过代码问题。

代码:

    unsigned int rings = 12, sectors = 24;

    float const R = 1./(float)(rings-1);
    float const S = 1./(float)(sectors-1);
    int r, s;

    vertices.resize(rings * sectors * 3);
    normals.resize(rings * sectors * 3);
    texcoords.resize(rings * sectors * 2);
    std::vector<GLfloat>::iterator v = vertices.begin();
    std::vector<GLfloat>::iterator n = normals.begin();
    std::vector<GLfloat>::iterator t = texcoords.begin();
    for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
            float const y = sin( -M_PI_2 + M_PI * r * R );
            float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
            float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

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

            *v++ = x * getR();
            *v++ = y * getR();
            *v++ = z * getR();

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

    indices.resize(rings * sectors * 4);
    std:vector<GLushort>::iterator i = indices.begin();
    for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
            *i++ = r * sectors + s;
            *i++ = r * sectors + (s+1);
            *i++ = (r+1) * sectors + (s+1);
            *i++ = (r+1) * sectors + s;
    }

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

    glVertexPointer(3, GL_FLOAT, 0, vertices.data());
    glNormalPointer(GL_FLOAT, 0, normals.data());
    glTexCoordPointer(2, GL_FLOAT, 0, texcoords.data());
    glDrawElements(GL_QUADS, indices.size(), GL_UNSIGNED_SHORT, indices.data());

代码取自(使用 Visual C++ 在 Opengl 中创建 3D 球体

4

1 回答 1

4

索引将以顶点之外的索引结束。索引中的最后四个值将是:

*i++ = 11 * 24 + 23 = 287;
*i++ = 11 * 24 + (23 + 1) = 288;
*i++ = (11 + 1) * 24 + (23 + 1) = 312;
*i++ = (11 + 1) * 24 + 23 = 311;

但 vertices 只包含 288 个顶点。我假设它对其他人有效的原因是 glDrawElements 可能会在某些实现中包装索引。

于 2013-04-11T14:55:12.403 回答