使用OpenGL绘制球体



有人能告诉我我把代码的哪一部分搞砸了吗?

在glDrawElements中,我只得到了带有";index.size((/3",大多数教程都是这样进行的,但当我尝试indices.size()时,我出现了分割错误,什么都没有出现。

vector<GLfloat> vertices, normals, texCoords;
vector<GLushort> indices;
void setupSphere(double r, int slice, int stack)
{
vertices.resize(slice * stack * 3);
normals.resize(slice * stack * 3);
texCoords.resize(slice * stack * 2);
float x, y, z, xz;
float nx, ny, nz, lengthInv = 1.0f / r;
float s, t;
float sliceAngle, stackAngle;
vector<GLfloat>::iterator itV = vertices.begin();
vector<GLfloat>::iterator itN = normals.begin();
vector<GLfloat>::iterator itT = texCoords.begin();
for (int i = 0; i < stack; i++)
{
stackAngle = M_PI_2 - M_PI * i / stack;
xz = r * cosf(stackAngle);
y = r * sinf(stackAngle);
for (int j = 0; j < slice; j++)
{
sliceAngle = 2 * M_PI * j / slice;
x = xz * sinf(sliceAngle);
z = xz * cosf(sliceAngle);
*itV++ = x;
*itV++ = y;
*itV++ = z;
nx = x * lengthInv;
ny = y * lengthInv;
nz = z * lengthInv;
*itN++ = nx;
*itN++ = ny;
*itN++ = nz;
s = (float)j / slice;
t = (float)i / stack;
*itT++ = s;
*itT++ = t;
}
}
int first, second;
for (int i = 0; i < stack; i++)
{
for (int j = 0; j < slice; j++)
{
first = i * slice + j;
second = first + slice + 1;
indices.push_back(first);
indices.push_back(second);
indices.push_back(first + 1);
indices.push_back(first + 1);
indices.push_back(second);
indices.push_back(second + 1);
}
}
}
void drawSphere()
{
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
glNormalPointer(GL_FLOAT, 0, &normals[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &texCoords[0]);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
}

正确的是indices.size() / 3,因为您必须传递三角形的数量,而不是索引的数量

正确的是indices.size(),因为您必须传递要传递的数组中的元素数。我不知道你看到的教程为什么使用/ 3变体。

关于缺少球体部分的问题,根据所提供的信息,我的最佳猜测是,您有超过65535个顶点,因此索引会围绕该值,因为您使用的是GL_UNSIGNED_SHORT

尝试从vector<GLushort> indices;更改为vector<GLuint> indices;,并在glDrawElements()中使用GL_UNSIGNED_INT

或者,降低slicestack的值,使得slice * stack * 3 <= 65535

生成N堆栈和M切片。因此,您可以创建(N-1(x(M-1(四边形
四边形的索引为(first,first+slice,first+1,first+slice+1(,其中first是四边形的第一个索引:

for (int i = 0; i < stack-1; i++)
{
for (int j = 0; j < slice-1; j++)
{
int first = i*slice + j;
unsigned short qi[]{first, first+slice, first+1, first+slice+1};
indices.insert(indices.end(), {qi[0], qi[2], qi[3], qi[0], qi[3], qi[1]});
}
}

请参阅"球体计算"one_answers"如何将纹理映射到使用点基元的参数方程渲染的球体"问题的答案。

最新更新