I'm trying to programmatically generate vertices and indices for a torus. I found this piece of code somewhere, and it looks like it works, but I'm not certain it is correct.
With my little knowledge of trigonometry, I figured out how the vertex generation part works, but I'm stuck at the index buffer part (though I know what the modulus operator is used for).
Does the code work correctly? Can anyone explain what it does to generate the correct indices?
I tried to output the index buffer and noticed there's a triangle with indices (10,10,10)
, which is weird and makes me think this may be wrong. Plus the UVs look weird for the last 'slice' of the torus, as in this pic.
int sides = 10, cs_sides = 40;
float radius = 3.5 * 10.0;
float cs_radius = 0.75 * 10.0;
numVertices = sides * cs_sides;
Vertices = malloc(sizeof(Vertex) * numVertices);
numIndices = (2 * ((sides+1) * cs_sides) + cs_sides);
Indices = malloc(sizeof(GLushort) * numIndices);
int angleincs = 360/sides;
int cs_angleincs = 360/cs_sides;
float currentradius, zval;
//calculating the vertex array
for (int j=0, m=0; j<360; j+=cs_angleincs, m++)
{
currentradius = radius + (cs_radius * cosf(j * D_TO_R ));
zval = cs_radius * sinf(j * D_TO_R );
int index = (m*sides);
for (int i=0, n=0; i<360; i+=angleincs, n++)
{
Vertices[index + n].Position[0] = currentradius * cosf(i * D_TO_R ); // x
Vertices[index + n].Position[1] = currentradius * sinf(i * D_TO_R ); // y
Vertices[index + n].Position[2] = zval; // z
Vertices[index + n].Color[0] = 1.0;
Vertices[index + n].Color[1] = 0.0;
Vertices[index + n].Color[2] = 0.0;
Vertices[index + n].Color[3] = 1.0;
float u = (float)i/sides;
float v = ((float)j + u)/cs_sides;
Vertices[index + n].TexCoord[0] = u;
Vertices[index + n].TexCoord[1] = v;
}
}
// cs_sides = 40
// sides = 10
int i=0, n=0;
//calculating the index array
for (;i<cs_sides; i++) {
for (int j=0; j<sides; j++) {
Indices[n++] = i * sides + j;
Indices[n++] = ((i+1) % cs_sides) * sides + j;
}
Indices[n++] = i * sides;
Indices[n++] = ((i+1)%cs_sides) * sides;
Indices[n++] = ((i+1)%cs_sides) * sides;
}