尝试实现我在 stackoverflow 上找到的球体示例代码时遇到了问题。请注意,我没有使用绘图代码,而是使用void SolidSphere
此示例中的函数来创建我的顶点数据。
这是我的代码,对我引用的示例进行了一些细微的更改:
std::vector<GLfloat> vertices;
std::vector<GLfloat> normals;
std::vector<GLfloat> texcoords;
std::vector<GLushort> indices;
Sphere(shared_ptr<GL::Shader> _shader, shared_ptr<Material> _material, float radius, unsigned int rings, unsigned int sectors)
{
this->attachShader(_shader);
this->attachMaterial(_material);
/** Implementation from:
https://stackoverflow.com/questions/5988686/how-do-i-create-a-3d-sphere-in-opengl-using-visual-c?lq=1
**/
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 = sphere_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 * radius;
*v++ = y * radius;
*v++ = z * radius;
//*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;
}
}
/************* THIS IS THE ADDED PART ********/
for (unsigned int i = 0; i < vertices.size(); i += 3) {
vertexCoords.push_back(glm::vec4(vertices[i], vertices[i+1], vertices[i+2], 1));
}
for (unsigned int i = 0; i < texcoords.size(); i += 2) {
textureCoords.push_back(glm::vec2(texcoords[i], texcoords[i+1]));
}
indexElements = indices;
cout << "Vertex vector size: " << vertexCoords.size() << endl;
cout << "Texture vector size: " << textureCoords.size() << endl;
cout << "Element index vector size: " << indexElements.size() << endl;
}
这里唯一的大变化是使用M_PI / 2
而不是M_PI_2
和两个循环将值推入我的代码使用的格式,即:
vector <glm::vec4> vertexCoords;
vector <glm::vec2> textureCoords;
vector <GLushort> indexElements;
这是我正在渲染的图片:
所以我看到球体顶部的最后一行..
有什么明显的我在这段代码中做错了可能导致这种情况的吗?