I'm trying to generate vertices and indices for a torus programmatically. I found this piece of code somewhere, and it looks like it works, but I'm not 100% sure it is correct.
With my little knowledge of trigonometry I figured out how the vertices generation part works, but I'm stuck at the index buffer part (except I know what the modulus operator is used for). Can anyone explain what it does to generate the correct indices? And can you confirm it is correct? I tried to output the index buffer and I noticed there's a triangle with indices (10,10,10), which is really weird and makes me think this may not even be correct. Plus the UVs look weird for the last 'slice' of the torus, as shown in this pic. Please enlighten me. Thanks.
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;
}




