通过构建圆形顶点,再将这些顶点组合成三角形,即可得出最后的图形。
纹理坐标就是通过投影计算得出。
代码
- 构建类
- 运行结果
构建类
#pragma once
#include <vector>
#include <glm/glm.hpp>
using namespace std;
class Ellipsoid
{
private:
//顶点个数
int numVertices;
//索引个数
int numIndices;
//顶点
vector<glm::vec3> vertices;
//法线
vector<glm::vec3> normals;
//纹理坐标
vector<glm::vec2> texCoords;
//索引
vector<int> indices;
//x轴向长度
float xAxis;
//y轴向长度
float yAxis;
//z轴向长度
float zAxis;
float toRadians(float degrees);
//初始化,计算各种数据
void init(int prec);
public:
Ellipsoid();
Ellipsoid(float xAxis, float yAxis, float zAxis, int prec);
int getNumVertices();
int getNumIndices();
vector<glm::vec3> getVertices();
vector<glm::vec3> getNormals();
vector<glm::vec2> getTexCoords();
vector<int> getIndices();
};
#include "Ellipsoid.h"
float Ellipsoid::toRadians(float degrees) { return (degrees * 2.0f * 3.14159f) / 360.0f; }
void Ellipsoid::init(int prec)
{
numVertices = (prec + 1) * (prec + 1);
numIndices = prec * prec * 6;
for (int i = 0; i < numVertices; i++)
{
vertices.push_back(glm::vec3());
normals.push_back(glm::vec3());
texCoords.push_back(glm::vec2());
}
for (int i = 0; i < numIndices; i++)
{
indices.push_back(0);
}
for (int i = 0; i <= prec; i++)
{
for (int j = 0; j <= prec; j++)
{
float x = xAxis * sin(toRadians(i * 180.f / prec)) * cos(toRadians(j * 360.f / prec));
float y = yAxis * sin(toRadians(i * 180.f / prec)) * sin(toRadians(j * 360.f / prec));
float z = zAxis * cos(toRadians(i * 180.0f / prec));
vertices[i * (prec + 1) + j] = glm::vec3(x, y, z);
normals[i * (prec + 1) + j] = glm::vec3(x, y, z);
texCoords[i * (prec + 1) + j] = glm::vec2((float)j / prec, (float)i / prec);
}
}
//计算索引
for (int i = 0; i < prec; i++) {
for (int j = 0; j < prec; j++) {
indices[6 * (i * prec + j) + 0] = i * (prec + 1) + j;
indices[6 * (i * prec + j) + 1] = i * (prec + 1) + j + 1;
indices[6 * (i * prec + j) + 2] = (i + 1) * (prec + 1) + j;
indices[6 * (i * prec + j) + 3] = i * (prec + 1) + j + 1;
indices[6 * (i * prec + j) + 4] = (i + 1) * (prec + 1) + j + 1;
indices[6 * (i * prec + j) + 5] = (i + 1) * (prec + 1) + j;
}
}
}
Ellipsoid::Ellipsoid(){}
Ellipsoid::Ellipsoid(float xAxis, float yAxis, float zAxis, int prec)
{
this->xAxis = xAxis;
this->yAxis = yAxis;
this->zAxis = zAxis;
init(prec);
}
int Ellipsoid::getNumVertices()
{
return numVertices;
}
int Ellipsoid::getNumIndices()
{
return numIndices;
}
vector<glm::vec3> Ellipsoid::getVertices()
{
return vertices;
}
vector<glm::vec3> Ellipsoid::getNormals()
{
return normals;
}
vector<glm::vec2> Ellipsoid::getTexCoords()
{
return texCoords;
}
vector<int> Ellipsoid::getIndices()
{
return indices;
}
运行结果